byte[] buffer = new byte[1024];
String s;
// Create a socket to listen on the port.
DatagramSocket socket = new DatagramSocket(port);
for(;;) {
// Create a packet with an empty buffer to receive data
// Bug workaround: create a new packet each time through the loop.
// If we create the packet outside of this loop, then it seems to
// loose track of its buffer size, and incoming packets are
// truncated.
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
// Wait to receive a datagram
socket.receive(packet);
// Convert the contents to a string
s = new String(buffer, 0, 0, packet.getLength());
// And display them
System.out.println("UDPReceive: received from " +
packet.getAddress().getHostName() + ":" +
packet.getPort() + ": " + s);
}