多线程完成在线咨询练习

多线程完成在线咨询:

发送线程:

	DatagramSocket socket = null;
    BufferedReader reader =null;

    private int fromPort;
    private String toIP;
    private int toPort;

    public TalkSend01(int fromPort,String toIP,int toPort) {
        this.fromPort = fromPort;
        this.toIP = toIP;
        this.toPort = toPort;

        try{
            socket = new DatagramSocket(fromPort);
            reader = new BufferedReader(new InputStreamReader(System.in));
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    @Override
    public void run() {
        while (true){
            try {
                String data = reader.readLine();
                byte[] datas = data.getBytes();
                DatagramPacket packet = new DatagramPacket(datas,0,datas.length,new InetSocketAddress(this.toIP,this.toPort));

                socket.send(packet);
                if (data.equals("bye")){
                    break;
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        socket.close();
    }

接收线程:

 	DatagramSocket socket = null;
    private int port;
    private String msg;
    public TalkReceive(int port,String msg){
        this.port =port;
        this.msg = msg;
        try{
            socket = new DatagramSocket(port);
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    @Override
    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 receive = new String(data,0,data.length);
                System.out.println(msg+":"+receive);

                if (receive.equals("bye")){
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        socket.close();
    }

开启线程:

  • 学生端:

    		new Thread(new TalkSend01(7777, "localhost", 9999)).start();
            new Thread(new TalkReceive(8888, "老师")).start();
    

    效果图:
    多线程完成在线咨询练习_第1张图片

  • 老师端:

    		new Thread(new TalkSend01(5555, "localhost", 8888)).start();
            new Thread(new TalkReceive(9999, "学生")).start();
    

    效果图:
    多线程完成在线咨询练习_第2张图片


学习地址:https://space.bilibili.com/95256449

你可能感兴趣的:(Java基础)