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:

To receive a datagram: 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.