多线程实现双人聊天

这个demo模拟了老师和学生的对话聊天功能。使用网络编程和多线程方式实现。

实现模拟老师和学生聊天的关键点就是 学生端既可以是发送方,也可以是接收方老师端同样既可以是发送方,也可以是接收方这样的话学生端需要同时开启接收和发送程序,老师端也要同时开启接收和发送程序学生端的发送程序端口对应老师端的接收程序端口,老师端的发送程序端口对应学生端的接收程序端口。

接收方

public class TalkReceive implements Runnable {
    private String sender;
    private DatagramSocket socket = null;
    private int port;

    public TalkReceive(int port,String sender) throws SocketException {
        this.port = port;
        this.sender = sender;
        //服务器的端口
        socket = new DatagramSocket(port);
    }

    public void run() {
        while (true) {
                try {
                    byte[] container = new byte[1024];
                    DatagramPacket packet = new DatagramPacket(container, 0, container.length);
                    socket.receive(packet);
                    byte[] data = packet.getData();
                    String msg = new String(data, 0, data.length);
                    System.out.println(this.sender + "对你说: " + msg);
                    if (msg.equals("bye")){
                        socket.close();
                        break;
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
        }

    }
}

发送方

public class TalkSend implements Runnable {

    private DatagramSocket socket = null;

    private BufferedReader reader = null;

    private int sendPort; //发送端口

    private String ip;//发送到的ip

    private int fromPort;//接收方端口

    public TalkSend(int sendPort, String ip, int fromPort) throws SocketException {
        this.sendPort = sendPort;
        this.ip = ip;
        this.fromPort = fromPort;
        this.socket = new DatagramSocket(fromPort);
        this.reader = new BufferedReader(new InputStreamReader(System.in));

    }

    public void run() {
        while (true) {
            try {
                String data = reader.readLine();
                byte[] bytes = data.getBytes();
                DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length, new InetSocketAddress(this.ip, this.sendPort));
                socket.send(packet);
                if ("bye".equals(data)) {
                    break;
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        socket.close();

    }
}

注意:

多线程实现双人聊天

查看控制台

多线程实现双人聊天
多线程实现双人聊天

匿名

发表评论

匿名网友