How do I create a simple Datagram server?
Created May 4, 2012
Tim Rohaly
The full source for a UDP echo server
and client can be downloaded from the following links:
To create a server with UDP, do the following:
- Create a DatagramSocket attached to a port.
int port = 1234; DatagramSocket socket = new DatagramSocket(port);
- 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);
- Block until a packet is received, then extract the information you need from the packet.
// Block on receive() socket.receive(packet); // 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.