UDP协议聊天室(基础)(练习)

按照下面的要求实现程序:
UDP发送数据:数据来自于键盘录入,直到输入“再见”,发送数据结束
UDP接收数据:死循环接收

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 SendDemo {
    
    
    //发送数据
    public static void main(String[] args) throws IOException {
    
    
        DatagramSocket ds = new DatagramSocket();
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String line;
        while ((line = br.readLine())!=null){
    
    
            if ("再见".equals(line)){
    
    
                break;
            }else {
    
    
                byte[] b = line.getBytes();
                DatagramPacket dp = new DatagramPacket(b,b.length, InetAddress.getByName("192.168.1.3"),6666);
                ds.send(dp);
            }
        }
            ds.close();
    }
}
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class ReceiveDemo {
    
    
    //接收数据
    public static void main(String[] args) throws IOException {
    
    
        DatagramSocket ds = new DatagramSocket(6666);
        while (true) {
    
    
            byte[] b = new byte[1024];
            DatagramPacket dp = new DatagramPacket(b,b.length);
            ds.receive(dp);
            System.out.println("XXX说:"+new String(dp.getData(),0,dp.getLength()));
        }
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_45380885/article/details/113925536