public class ReceiveDemo {
public static void main(String[] args) throws IOException {
//创建接收端的socket对象
DatagramSocket ds=new DatagramSocket(12345);
//创建一个包裹
byte[] bs=new byte[1024];
DatagramPacket dp=new DatagramPacket(bs, bs.length);
//接收数据
ds.receive(dp);
//解析数据,链式编程
String ip=dp.getAddress().getHostAddress();
String s=new String(dp.getData(),0,dp.getLength());
System.out.println("from"+ip+"data is:"+s);
//释放资源
ds.close();
}
}
public class SendDemo {
public static void main(String[] args) throws IOException {
//创建发送端的socket对象
DatagramSocket ds= new DatagramSocket();
//创建数据并打包
byte[] bs="helloworld".getBytes();
DatagramPacket dp=new DatagramPacket(bs, bs.length,InetAddress.getByName("192.168.137.1"),12345);
//发送数据
ds.send(dp);
//释放资源
ds.close();
}
}