Sending Datagrams

Now that we’ve thoroughly covered the possibilities of networking with sockets and streams, let’s examine how low-level networking can be done using datagrams and packets. Examples Example 5-11 and Example 5-12 show how you can implement simple network communication using datagrams. Datagram communication is sometimes called UDP, for Unreliable Datagram Protocol. Sending datagrams is fast, but the trade-off is that they are not guaranteed to reach their destination. In addition, multiple datagrams are not guaranteed to travel to their destination by the same route or to arrive at their destination in the order in which they were sent. Datagrams are useful when you want low-overhead communication of noncritical data and when a stream model of communication is not necessary. For example, you might implement a multiuser chat server for a local area network using datagrams.

To send and receive datagrams, you use the DatagramPacket and DatagramSocket classes. These objects are created and initialized differently, depending on whether they send or receive datagrams. Example 5-11 shows how to send a datagram; Example 5-12 shows how to receive a datagram and how to find who sent it.

To send a datagram, you first create a DatagramPacket, specifying the data to be sent, the length of the data, the host to send it to, and the port on that host where it is to be sent. You then use the send( ) method of a DatagramSocket to send the packet. The DatagramSocket is a generic ...

Get Java Examples in a Nutshell, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.