public class send {
public static void main(String[] args) throws IOException, InterruptedException {
Scanner sc = new Scanner(System.in);
DatagramSocket socket = new DatagramSocket();
while (true) {
String line = sc.nextLine();
if ("exit".equals(line)) {
break;//当输入exit时退出
}
DatagramPacket packet = new DatagramPacket(line.getBytes(), line.getBytes().length,
InetAddress.getByName("127.0.0.1"), 9999);//创建packet,指定数据、长度、地址和端口
socket.send(packet);
}
socket.close();
}
}
public class receive {
public static void main(String args[]) throws IOException {
DatagramSocket socket = new DatagramSocket(9999);
DatagramSocket socket = new DatagramSocket(9999);
DatagramPacket packet = new DatagramPacket(new byte[1024], 1024);
while(true) {
socket.receive(packet);
String ip = packet.getAddress().getHostAddress();
byte[] arr = packet.getData();//创建数组存储packet中的数据
int len = packet.getLength();
System.out.println("IP:"+ip+" "+new String(arr,0,len));
}
}
}
先执行receive类再执行send类
运行结果: