Datagram Sockets
TinyHttpd
used a Socket to create a connection to the client
using the TCP protocol. In that example, TCP itself took care of data
integrity; we didn’t have to worry about data arriving out of
order or incorrect. Now we’ll take a walk on the wild side.
We’ll build 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,
but we didn’t have to worry about those details.)
UDP doesn’t guarantee that the data will get through. If the data packets do get through, they may not arrive in the order in which we sent them; 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 got 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. But it’s significantly more efficient ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access