How do I create a simple Datagram server?

Tim Rohaly

To create a server with UDP, do the following:

  1. Create a DatagramSocket attached to a port.
    int port = 1234;
    DatagramSocket socket = new DatagramSocket(port);
  2. Allocate space to hold the incoming packet, and create an instance of DatagramPacket to hold the incoming data.
    byte[] buffer = new byte[1024];
    DatagramPacket packet =
           new DatagramPacket(buffer, buffer.length);
  3. Block until a packet is received, then extract the information you need from the packet.
    // Block on receive()
    // Find out where packet came from
    // so we can reply to the same host/port
    InetAddress remoteHost = packet.getAddress();
    int         remotePort = packet.getPort();
    // Extract the packet data
    byte[]      data       = packet.getData();

The server can now process the data it has received from the client, and issue an appropriate reply in response to the client's request.

The full source for a UDP echo server and client can be downloaded from the following links: