Datagram (UDP) Sockets
Unlike TCP/IP sockets, datagram sockets are connectionless . That is to say, the con-
nection between client and server is not maintained throughout the duration of the
dialogue. Instead, each datagram packet is sent as an isolated transmission whenever
necessary. As noted in Chap. 1 , datagram (UDP) sockets provide a (usually) faster
means of transmitting data than TCP/IP sockets, but they are unreliable.
Since the connection is not maintained between transmissions, the server
does not create an individual Socket object for each client, as it did in our TCP/
IP example. A further difference from TCP/IP sockets is that, instead of a
ServerSocket object, the server creates a DatagramSocket object, as does each
client when it wants to send datagram(s) to the server. The fi nal and most sig-
nifi cant difference is that DatagramPacket objects are created and sent at both
ends, rather than simple strings.
Following the style of coverage for TCP client/server applications, the detailed
steps required for client and server will be described separately, with the server
process being covered fi rst. This process involves the following nine steps, though
only the fi rst eight steps will be executed under normal circumstances…
1. Create a DatagramSocket object.
Just as for the creation of a ServerSocket object, this means supplying the object's
constructor with the port number. For example:
DatagramSocket datagramSocket =
2. Create a buffer for incoming datagrams.
This is achieved by creating an array of bytes. For example:
byte buffer = new byte;
3. Create a DatagramPacket object for the incoming datagrams.
The constructor for this object requires two arguments:
the previously-created byte array;
the size of this array.
DatagramPacket inPacket =
new DatagramPacket(buffer, buffer.length);
4. Accept an incoming datagram.
This is effected via the receive method of our DatagramSocket object, using our
DatagramPacket object as the receptacle . For example: