Datagram Sockets
TinyHttpd used a Socket to create a connection to the client
using the TCP protocol. In that example, the TCP protocol took care of
data integrity; we didn’t have to worry about data arriving out of order
or incorrect. Now, let’s take a walk on the wild side, building an applet
that uses a java.net.DatagramSocket,
which uses the UDP protocol. A datagram is sort of like a letter sent via
the postal service: it’s a discrete chunk of data transmitted in one
packet. Unlike the previous example, where we could get a convenient
OutputStream from our Socket and write the data as if writing to a
file with a DatagramSocket, we have to
work one datagram at a time. (Of course, the TCP protocol was taking our
OutputStream and slicing the data into
packets, too, but we didn’t have to worry about those details.)
UDP doesn’t guarantee that the data is received. If the data packets are received, they may not arrive in the order in which they were sent; it’s even possible for duplicate datagrams to arrive (under rare circumstances). Using UDP is something like cutting the pages out of the encyclopedia, putting them into separate envelopes, and mailing them to your friend. If your friend wants to read the encyclopedia, it’s his or her job to put the pages in order. If some pages get lost in the mail, your friend has to send you a letter asking for replacements.
Obviously, you wouldn’t use UDP to send a huge amount of data without error correction. However, it’s significantly more ...