Package com. socket. demo; Import java.net. DatagramPacket; Import java.net. DatagramSocket; Public class ReceiveDemo implements Runnable { Private DatagramSocket ds; Public ReceiveDemo (DatagramSocket ds ){ This. ds = ds; } @ Override Public void run (){ Try { While (true ){ // 2. Create a data packet. Byte [] buf = new byte [1, 1024]; DatagramPacket dp = new DatagramPacket (buf, buf. length ); // 3. Use the Receiving Method to store data in the data packet. Ds. receive (dp); // blocked. // 4. parse the data in the data packet object, such as the address, port, and data content. String ip = dp. getAddress (). getHostAddress (); Int port = dp. getPort (); System. out. println ("---- port -----" + port ); String text = new String (dp. getData (), 0, dp. getLength ()); System. out. println (ip + ":" + text ); If (text. equals ("886 ")){ System. out. println (ip + "... quit chatting room "); } } } Catch (Exception e ){ } } } |