网络编程——(4)UDP协议——多线程、多人聊天室

   

     

先要创建一个聊天室,往同一个IP、端口下发送消息大家都可以查看。输入886时退出聊天室

一、首先编写发送消息

public class Send implements Runnable{

    private DatagramSocket ds;

    public Send(DatagramSocket ds) {
        this.ds = ds;
    }

    @Override
    public void run() {
        try {
            //从键盘录入
            BufferedReader bufr =new BufferedReader(new InputStreamReader(System.in));
            String line =null;
            while ((line=bufr.readLine())!=null){
                //将字符装换成字节
                byte[] buf=line.getBytes();
                //封装数据以及发送地址端口
                DatagramPacket  dp =new DatagramPacket(buf,buf.length, InetAddress.getByName("127.0.0.1"),9999);
                //发送数据
                ds.send(dp);
                //当键盘输入886时,退出聊天室
                if ("886".equals(line)){
                    break;
                }
            }
            //关闭资源
            ds.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

二、编写接收消息

public class Rece implements Runnable {
    
    private DatagramSocket ds;

    public Rece(DatagramSocket ds) {
        this.ds = ds;
    }
    @Override
    public void run() {
        try {
            
            //一直处于接收状态
            while (true) {

                // 2,创建数据包。
                byte[] buf = new byte[1024];
                DatagramPacket dp = new DatagramPacket(buf, buf.length);

                // 3,使用接收方法将数据存储到数据包中。
                ds.receive(dp);// 阻塞式的。

                // 4,通过数据包对象的方法,解析其中的数据,比如,地址,端口,数据内容。
                String ip = dp.getAddress().getHostAddress();
                int port = dp.getPort();
                String text = new String(dp.getData(), 0, dp.getLength());

                System.out.println(ip + "::" + text);
                if(text.equals("886")){
                    System.out.println(ip+"....退出聊天室");
                }
            }
        } catch (Exception e) {
        }
    }
}

三、主程序、创建线程、装载任务、启动线程

public class ChatDemo {

    public static void main(String[] args) throws SocketException {
        //创建 发送和接收套接字对象 其中接收套接字端口需和发送的端口保持一致
        DatagramSocket send =new DatagramSocket();
        DatagramSocket rece =new DatagramSocket(9999);

        //新建线程,转载任务,启动线程
        new Thread(new Send(send)).start();
        new Thread(new Rece(rece)).start();
    }

}

由于只有本机一个环境,所以暂时无法测试多人在线聊天。但是源码是可以用的。

、 

发布了186 篇原创文章 · 获赞 45 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/zhanshixiang/article/details/104039729