Java Reference
In-Depth Information
is available, read() blocks until at least 1 byte can be read or the end-of-stream is
detected, indicated by a return of
1.
data
Buffer to receive data from input stream
offset
Starting byte of data in which to write
length
Maximum number of bytes to read
int available ()
Returns the number of bytes available for input.
void close ()
Terminates the stream.
2.3
UDP Sockets
UDP provides an end-to-end service different from that of TCP. In fact, UDP performs only
two functions: 1) it adds another layer of addressing (ports) to that of IP, and 2) it detects
data corruption that may occur in transit and discards any corrupted messages. Because of
this simplicity, UDP sockets have some different characteristics from the TCP sockets we saw
earlier. For example, UDP sockets do not have to be connected before being used. Where TCP
is analogous to telephone communication, UDP is analogous to communicating by mail: you
do not have to “connect” before you send a package or letter, but you do have to specify
the destination address for each one. Similarly, each message—called a datagram —carries its
own address information and is independent of all others. In receiving, a UDP socket is like
a mailbox into which letters or packages from many different sources can be placed. As soon
as it is created, a UDP socket can be used to send/receive messages to/from any address and
to/from many different addresses in succession.
Another difference between UDP sockets and TCP sockets is the way that they deal with
message boundaries: UDP sockets preserve them . This makes receiving an application message
simpler, in some ways, than it is with TCP sockets. (This is discussed further in Section 2.3.4.) A
final difference is that the end-to-end transport service UDP provides is best-effort: there is no
guarantee that a message sent via a UDP socket will arrive at its destination, and messages can
be delivered in a different order than they were sent (just like letters sent through the mail).
A program using UDP sockets must therefore be prepared to deal with loss and reordering.
(We'll provide an example of this later.)
Given this additional burden, why would an application use UDP instead of TCP? One
reason is eciency: if the application exchanges only a small amount of data—say, a single
request message from client to server and a single response message in the other direction—
TCP's connection establishment phase at least doubles the number of messages (and the
number of round-trip delays) required for the communication. Another reason is flexibility:
when something other than a reliable byte-stream service is required, UDP provides a minimal-
overhead platform on which to implement whatever is needed.
Java programmers use UDP sockets via the classes DatagramPacket and DatagramSocket .
Both clients and servers use DatagramSocket s to send and receive DatagramPacket s.
Search WWH ::




Custom Search