发送端:
package chat;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
public class UDPSenderDemo1 {
public static void main(String[] args) throws Exception {
DatagramSocket socket=new DatagramSocket(8888);
//准备数据,控制台读取System.in
BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));
while(true){
String data=reader.readLine();
byte[] bytes=data.getBytes();
DatagramPacket packet=new DatagramPacket(bytes,0,bytes.length,new InetSocketAddress("127.0.0.1",9090));
socket.send(packet);
if (data.equals("bye")){
break;
}
}
socket.close();
}
}
接收端:
package chat;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class UDPRecieverDemo1 {
public static void main(String[] args) throws Exception {
DatagramSocket socket=new DatagramSocket(9090);
while(true){
//准备接收包裹
byte[] container=new byte[1024];
DatagramPacket packet=new DatagramPacket(container,0,container.length);
socket.receive(packet);//阻塞式接收包裹
//断开连接
byte[] data=packet.getData();
String recieveData=new String(data,0,packet.getLength());
System.out.println(recieveData);
if (recieveData.equals("bye")){
break;
}
}
socket.close();
}
}
UDP聊天实现