public class UDP_Client {
public static void main(String[] args) throws Exception {
//1、创建服务 + 端口
DatagramSocket client = new DatagramSocket(6666);
//2、准备数据
String msg = "我喜欢你" ;
byte[] data = msg.getBytes();
//3、打包(发送地点+端口)
DatagramPacket packet =
new DatagramPacket(data, data.length , new InetSocketAddress("localhost" ,8888));
//4、发送
client.send(packet);
//5、释放
client.close();
}
}
public class UDP_Server {
public static void main(String[] args) throws Exception {
//1、创建服务端+端口
DatagramSocket server = new DatagramSocket(8888);
//2、准备容器接收
byte[] container = new byte[1024];
//3、封装成包
DatagramPacket packet = new DatagramPacket(container,container.length );
//4、接受数据
server.receive(packet);
//5、分析数据
byte[] data = packet.getData();
int len = packet.getLength();
System. out.println(new String(data, 0, len));
//6、释放
server.close();
}
}