首页 > 其他分享 >UDP聊天实现

UDP聊天实现

时间:2023-03-17 11:58:53浏览次数:38  
标签:UDP datagramPacket socket 实现 聊天 new data datas String

 1 public class A {
 2     public static void main(String[] args) throws IOException {
 3         DatagramSocket socket = new DatagramSocket(8888);
 4         BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
 5         while (true) {
 6             //输出流像一根管子,你将数据输入到这个管子,然后他将数据通向data
 7             String data = reader.readLine();
 8             byte[] datas = data.getBytes();
 9             DatagramPacket datagramPacket = new DatagramPacket(datas, 0, datas.length, new InetSocketAddress(InetAddress.getLocalHost(), 6666));
10             socket.send(datagramPacket);
11             if(data.equals("bye")){
12                 break;
13             }
14         }
15         reader.close();
16         socket.close();
17 
18     }
19 }
public class B {
    public static void main(String[] args) throws IOException {
        DatagramSocket socket = new DatagramSocket(6666);
        while (true) {
            byte[] bytes = new byte[1024];
            DatagramPacket datagramPacket = new DatagramPacket(bytes, 0, bytes.length);
            socket.receive(datagramPacket);
            byte[] data = datagramPacket.getData();
            String datas = new String(data, 0,datagramPacket.getLength());
            System.out.println(datas);
            if (datas.equals("bye")) {
                break;
            }
        }
        socket.close();
    }
}

 

标签:UDP,datagramPacket,socket,实现,聊天,new,data,datas,String
From: https://www.cnblogs.com/guojianglong/p/17226151.html

相关文章