DatagramSocket and DatagramPacket
An alternative to TCP for network communication is UDP (Unreliable
Datagram Protocol). Sending datagrams is faster, but the tradeoff is
they are not guaranteed to reach their destination, and, a sequence of
datagrams are not guaranteed to be delivered in the order in which they
were sent. Datagrams are useful when you want low-overhead
communication of non-critical data and when a stream model of
communication is not necessary.
A datagram is a packet that is routed from one machine to another based
solely on information contained within the packet. A datagram socket
is a sending or receiving point. Each packet sent or received on a
datagram socket is individually addressed and routed. Multiple packets
sent from one machine to another may be routed differently, and may
arrive in any order.
The classes DatagramSocket and DatagramPacket
are used to send and receive datagrams. Instances of these classes are
created and initialized differently depending on whether they are being
used to send or receive datagrams.
To send a datagram:
- Create a generic DatagramSocket object by requesting its
default constructor
- Create a DatagramPacket object by specifying the data to
send, the length of the data, the destination host, and the destination port
- Pass the packet object as the parameter of the socket object's
send() method.
To receive a datagram:
- Create a DatagramSocket object that listens on a particular
port of the local host
- Create a DatagramPacket object with a byte
buffer large enough to hold the expected data (if the received data is bigger
than the buffer, the extra bytes will be discarded)
- Pass the packet object as the parameter of the socket object's
receive() method
- receive() will block until a datagram arrives
- When a datagram is received, it will contain its source host and source
port, as well as the actual data.
The example models two different executables with two threads. The
sleep() call was added to force the sending thread to
relinquish control of the CPU so that the receiving thread could
process the arriving packet.