1 package WebProgramingDemo; 2 3 import java.io.IOException; 4 import java.net.DatagramPacket; 5 import java.net.DatagramSocket; 6 7 public class UDPReceiveDemo { 8 9 /** 10 * @param args 11 * @throws IOException 12 */ 13 /* 14 * 创建UDP接收端的步骤: 15 * 1.建立UDP socket服务 16 * 2.创建数据包,用于存储接收到的数据,方便用数据包对象的方法解析这些数据 17 * 3.使用socket服务的receive方法将接收到的数据存储到包中 18 * 4,通过数据包的方法解析数据包中的数据 19 * 5,关闭资源 20 * 21 */ 22 23 public static void main(String[] args) throws IOException { 24 System.out.println("接收端启动。。。。"); 25 DatagramSocket ds1 = new DatagramSocket(10000); 26 byte bufre[] = new byte[1024]; 27 DatagramPacket dp1 = new DatagramPacket(bufre, bufre.length); 28 ds1.receive(dp1);//阻塞式方法 29 String ip = dp1.getAddress().getHostAddress(); 30 int port = dp1.getPort(); 31 String text = new String(dp1.getData(), 0, dp1.getLength()); 32 System.out.println(ip + ":" + port + ":" + text); 33 ds1.close(); 34 } 35 36 }