The following J2ME code snippet shows how to receive datagrams in a mobile application. To receive a datagram, you first have to allocate a Datagram object with a buffer large enough for the data that you expect to receive.

 DatagramConnection receiver =
byte[] buffer = new byte[256];
Datagram dgram = receiver.newDatagram(buffer, buffer.length);

for (;;) {
  int length = dgram.getLength( );
  System.out.println("Datagram received. Length is " + length);
  // Show the content of the datagram.
  for (int i = 0; i < length; i++) {
    System.out.print(buffer[i] + " ");



 Related Tips