Java网络编程之Socket&ServerSocket

最近学了点Java网络编程,多个客户端实现实时通信。

项目分为4个类  :消息类、消息类型类、服务器端类、客户端类。

消息类中 包括 String的消息内容、消息发送者、消息传达者,和int的消息类型。

package WeiXinItsFather;

import java.io.Serializable;

public class Message implements Serializable{
    private String from;
    private String to;
    private String info;
    private int type;
    public String getFrom() {
        return from;
    }
    public void setFrom(String from) {
        this.from = from;
    }
    public String getTo() {
        return to;
    }
    public void setTo(String to) {
        this.to = to;
    }
    public String getInfo() {
        return info;
    }
    public void setInfo(String info) {
        this.info = info;
    }
    public int getType() {
        return type;
    }
    public void setType(int type) {
        this.type = type;
    }
    public Message(String from, String to, String info, int type) {
        super();
        this.from = from;
        this.to = to;
        this.info = info;
        this.type = type;
    }
    @Override
    public String toString() {
        return "Message [from=" + from + ", to=" + to + ", info=" + info + ", type=" + type + "]";
    }
    
    public Message() {
        
    }
    
}
 

消息类型类 包括 两个静态int的变量,用于区别服务器处理客户端登录和发送操作

package WeiXinItsFather;

public final class MessageType {
    public static final int TYPE_LOGIN = 0x1;
    public static final int TYPE_SEND = 0x2;
    
}
 

服务器端类通过 容器Vector保存客户端处理的线程,通过ExecutorService 创建线程池,然后创建一个用户进程类UserThread 继承自 Runnable,重载run()函数:通过对象流获取消息对象,然后判断消息类型,若是登录则通过输出流返回“欢迎你”,若是发送类型则获取消息对象中的消息传达者,然后通过遍历容器中是否有“消息传达者”的客户端线程,有的话就将消息对象通过该线程的输出流发送出去。

package WeiXinItsFather;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Executable;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Vector;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Server {
    public static void main(String[] args) {
        Vector<UserThread> vector = new Vector<UserThread>();//保存客户端处理的线程
        ExecutorService es = Executors.newFixedThreadPool(5);
        try {
            ServerSocket server = new ServerSocket(6666);
            System.out.println("服务器已启动");
            while(true) {
                Socket socket = server.accept();
                UserThread user = new UserThread(socket, vector);
                es.execute(user);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        
    }
}

class UserThread implements Runnable{
    private Socket s;
    private Vector<UserThread> v;
    private String name;
    private ObjectInputStream ois;
    private ObjectOutputStream oos;
    private boolean flag = true;
    
    public UserThread(Socket s, Vector<UserThread> v) {
        this.s = s;
        this.v = v;
        v.add(this);
    }
    @Override
    public void run() {
        try {
            System.out.println("客户端已连接"+s.getInetAddress().getHostAddress());
            ois = new ObjectInputStream(s.getInputStream());
            oos = new ObjectOutputStream(s.getOutputStream());
             
            while (flag) {
                Message msg = (Message)ois.readObject();  //读取输入流对象
                int type = msg.getType();  //获取输入流对象中的类型
                switch (type) {  //判断输入流的对象类型
                case MessageType.TYPE_SEND:   //类型是发送信息
                    String info = msg.getTo();  //获取要送达消息的客户名称 
                    UserThread ut;  //创建一个用户线程
                    /**
                     * 判断 要送达消息的客户名称 是否存在(是否在vector中)
                     * 存在的话就把  发送消息的客户的消息内容(ois)写到 要送达消息的“客户通道”(oos)
                     */
                    for (int i = 0; i < v.size(); i++) {
                        ut = v.get(i);
                        if(info.equals(ut.name) && ut!=this) {
                            ut.oos.writeObject(msg);
                            break;
                        }
                    }
                    break;
                case MessageType.TYPE_LOGIN://类型是登录
                            name = msg.getFrom();
                            msg.setInfo("欢迎你:");
                            oos.writeObject(msg);
                    break;
                }
            }
            ois.close();
            oos.close();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
 

客户端类:创建线程,通过Socket连接服务器端,创建登录的消息对象,通过输出流发送到服务器;然后创建一个读输入流的线程ReadInfoThread,重载run()函数,实现获取输入流的消息对象(服务器发送来的);然后创建发送类型的消息对象,通过输出流发送给服务器端。

package WeiXinItsFather;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.*;

public class Client {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        ExecutorService es = Executors.newSingleThreadExecutor();
        
        try {
            Socket s = new Socket("localhost",6666);
            System.out.println("服务器连接成功");
            ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());
            ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
            
            System.out.println("请输入:");
            String name = input.nextLine();
            Message msg = new Message(name,null,null,MessageType.TYPE_LOGIN);
            oos.writeObject(msg);
            msg = (Message)ois.readObject(); 
            System.out.println(msg.getInfo()+msg.getFrom());
            
            es.execute(new ReadInfoThread(ois));
            
            boolean flag = true;
            
            while (flag) {
                msg = new Message();
                System.out.println("To:");
                msg.setTo(input.nextLine());
                msg.setFrom(name);
                msg.setType(MessageType.TYPE_SEND);
                System.out.println("请输入要发送的消息info:");
                String info = input.nextLine();
                msg.setInfo(info);
                oos.writeObject(msg);
            }
            
        } catch (IOException | ClassNotFoundException e) {
            // TODO: handle exception
        }
    }

}

class ReadInfoThread implements Runnable{
    private ObjectInputStream in;
    public ReadInfoThread(ObjectInputStream in) {
        this.in = in;
    }
    
    private boolean flag = true ;
    @Override
    public void run() {
    
        try {
            while(flag) {
                Message msg = (Message)in.readObject();
                System.out.println("["+msg.getFrom()+"]"+msg.getInfo());
            }
            
            if(in!=null)
            {
                in.close();
            }
        } catch (IOException | ClassNotFoundException e) {
            // TODO: handle exception
        }
    }
}
注:在网络通讯中,主机与客户端若使用ObjectInputStream与ObjectOutputStream建立对象通讯,必须注重声明此两个对象的顺序。 
如: 
主机端先建立ObjectInputStream后建立ObjectOutputStream,则对应地客户端要先建立ObjectOutputStream后建立ObjectInputStream,否则会造成两方互相等待数据而导致死锁。 
原因是建立ObjectInputStream对象是需要先接收一定的header数据,接收到这些数据之前会处于阻塞状态。

转载于:https://my.oschina.net/u/4069817/blog/3019527

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值