public class UDPReceiveDemo {
public static void main(String[] args) throws IOException {
//创建UDP接收端套接字对象
DatagramSocket ds = new DatagramSocket(10086);
//创建一个数据报,用于接收发来的数据
byte[] bys = new byte[1024];
int length = bys.length;
DatagramPacket dp = new DatagramPacket(bys, length);
//调用ds对象的receive()方法接收数据
ds.receive(dp);
System.out.println(dp.getLength());
//从接收到的包中读出信息
byte[] bys2 = dp.getData();
int realLen = dp.getLength();
String s = new String(bys2, 0, realLen);
InetAddress ia = dp.getAddress();
System.out.println( ia.getHostAddress() + "发来了"+ s);
//释放资源
ds.close();
}
}
public class UDPsendDemo {
public static void main(String[] args) throws IOException {
//创建发送端的UDP套接字对象
DatagramSocket ds = new DatagramSocket();
//创建数据报包
byte[] bys = "hello,UDP,我来了".getBytes();
int length = bys.length;
// InetAddress ia = InetAddress.getByName("PC-20200320HQPC");
InetAddress ia = InetAddress.getByName("192.168.42.194");
int port = 10086;
DatagramPacket dp = new DatagramPacket(bys, length, ia,port);
//调用Socket对象的send()方法
ds.send(dp);
//释放资源
ds.close();
}
}