java多线程聊天室基于UDP协议简单实现

如果有不正确的地方请指出。

发送端



package Socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class 线程控制send implements Runnable{

    private DatagramSocket socket;

    public 线程控制send(DatagramSocket socket) {
        this.socket= socket;
    }

    @Override
    public void run() {
            try {
                while(true) {
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
                    String line = null;
                    while ((line = bufferedReader.readLine()) != null) {
                        if ("告辞".equals(line))
                            break;
                        byte[] b = line.getBytes();
                        DatagramPacket datagramPacket = new DatagramPacket(b, b.length, InetAddress.getLocalHost(), 10000);
                        socket.send(datagramPacket);
                    }
                    socket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
        }
    }
}





接收端



package Socket;

import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class 线程控制Receive implements Runnable{
    private DatagramSocket socket;
    public 线程控制Receive(DatagramSocket socket) {
        this.socket = socket;
    }


    @Override
    public void run() {
        try {
            while (true) {
                byte[] b = new byte[1024];

                DatagramPacket datagramPacket = new DatagramPacket(b, b.length);
                socket.receive(datagramPacket);
                String ip = datagramPacket.getAddress().getHostAddress();
                int port = datagramPacket.getPort();
                String data = new String(datagramPacket.getData(), 0, datagramPacket.getLength());
                System.out.println(ip + port +"\r\n"+ data);
                if(data.equals("告辞")) {
                    System.out.println(ip + "......退出聊天室");
                    socket.close();
                }
            }
        }catch (Exception e){

        }
    }
}




main函数启动线程


package Socket;

import java.io.IOException;
import java.net.DatagramSocket;

public class UDPChat {
    public static void main(String[] args) throws IOException {

        DatagramSocket send = new DatagramSocket();
        DatagramSocket receive = new DatagramSocket(10000);
        线程控制send s=new 线程控制send(send);
        线程控制Receive r = new 线程控制Receive(receive);
        Thread b = new Thread(r);

        Thread a = new Thread(s);

       a.start();
       b.start();

    }

}

 

你可能感兴趣的:(java,多线程,UDP协议,java,多线程)