Package com. socket. demo; Import java. io. IOException; Import java.net. DatagramPacket; Import java.net. DatagramSocket; Public class UDPReceiveDemo2 { Public static void main (String [] args) throws IOException { System. out. println ("acceptor starts ............ "); /* 2. To create a UDP socket service, you must specify a port number. 3. Create a data packet to store the received data and use the data packet object method to parse the data. 4. Use the receive method of DatagramSocket to store the received data into the data packet. 5. parse the data in the data packet through the data packet Method 5. Disable the socket service. */ // Udpsocket service, using the initramsocket object DatagramSocket ds = new DatagramSocket (10003 ); While (true ){ // Use DatagramPacket to encapsulate data in this object Byte [] buf = new byte [1, 1024]; DatagramPacket dp = new DatagramPacket (buf, buf. length ); // Send data packets through the udp socket service. Ds. receive (dp); // blocked. // Parse the data in the data packet through the data packet method, such as the address, port, and data content. String ip = dp. getAddress (). getHostAddress (); // String name = dp. getAddress (). getHostName (); Int port = dp. getPort (); String text = new String (dp. getData (), 0, dp. getLength ()); // System. out. println ("-----" + ip + "-----" + name + "-----" + port + "-----" + text ); System. out. println ("-----" + ip + "----------" + port + "-----" + text ); } // Close the resource // Ds. close (); } } |