Receiving UDP Datagrams

To receive data sent to you, you construct a DatagramSocket object on the port on which you want to listen. Then you pass an empty DatagramPacket object to the DatagramSocket's receive() method.

public void receive(DatagramPacket dp) throws IOException

The calling thread blocks until the a datagram is received. Then dp is filled with the data from that datagram. You can then use getPort() and and getAddress() to tell where the packet came from, getData() to retrieve the data, and getLength() to see how many bytes were in the data. If the received packet was too long for the buffer, then it's truncated to the length of the buffer. For example,

try {
  byte buffer = new byte[65536]; // maximum size of an IP packet
  DatagramPacket incoming = new DatagramPacket(buffer, buffer.length);
  DatagramSocket ds = new DatagramSocket(2134);
  ds.receive(dp);
  byte[] data = dp.getData();
  String s = new String(data, 0, data.getLength());
  System.out.println("Port " + dp.getPort() + " on " + dp.getAddress()
   + " sent this message:");
  System.out.println(s);
}
catch (IOException ex) {
  System.err.println(ex);
}

Previous | Next | Top | Cafe au Lait

Copyright 1997 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified April 18, 1997