Java Reference
In-Depth Information
socket sends and receives all data directed to or from a port without any concern for
who the remote host is. A single DatagramSocket can send data to and receive data from
many independent hosts. The socket isn't dedicated to a single connection, as it is in
TCP. In fact, UDP doesn't have any concept of a connection between two hosts; it only
knows about individual datagrams. Figuring out who sent what data is the application's
responsibility. Second, TCP sockets treat a network connection as a stream: you send
and receive data with input and output streams that you get from the socket. UDP doesn't
support this; you always work with individual datagram packets. All the data you stuff
into a single datagram is sent as a single packet and is either received or lost as a group.
One packet is not necessarily related to the next. Given two packets, there is no way to
determine which packet was sent first and which was sent second. Instead of the orderly
queue of data that's necessary for a stream, datagrams try to crowd into the recipient as
quickly as possible, like a crowd of people pushing their way onto a bus. And occasion‐
ally, if the bus is crowded enough, a few packets, like people, may not squeeze on and
will be left waiting at the bus stop.
UDP Clients
Let's begin with a simple example. As in “Reading from Servers with Sockets” on page
240 we will connect to the daytime server at the National Institute for Standards and
Technology (NIST) and ask it for the current time. However, this time you'll use UDP
instead of TCP. Recall that the daytime server listens on port 13, and that the server
sends the time in a human-readable format and closes the connection.
Now let's see how to retrieve this same data programmatically using UDP. First, open a
socket on port 0:
DatagramSocket socket = new DatagramSocket ( 0 );
This is very different than a TCP socket. You only specify a local port to connect to. The
socket does not know the remote host or address. By specifying port 0 you ask Java to
pick a random available port for you, much as with server sockets.
The next step is optional but highly recommended. Set a timeout on the connection
using the setSoTimeout() method. Timeouts are measured in milliseconds, so this
statement sets the socket to time out after 10 seconds of nonresponsiveness:
socket . setSoTimeout ( 10000 );
Timeouts are even more important for UDP than TCP because many problems that
would cause an IOException in TCP silently fail in UDP. For example, if the remote
host is not listening on the targeted port, you'll never hear about it.
Next you need to set up the packets. You'll need two, one to send and one to receive.
For the daytime protocol it doesn't matter what data you put in the packet, but you do
need to tell it the remote host and remote port to connect to:
Search WWH ::




Custom Search