Java Reference
In-Depth Information
void
setData
(
byte[ ]
buffer
)
void
setData
(
byte[ ]
buffer
,
int
offset
,
int
length
)
Makes the given byte array the datagram buffer. The first form makes the entire byte
array the buffer; the second form makes bytes
offset
through
offset
1 the
buffer. The first form never updates the internal offset and only updates the internal
length if the given buffer's length is less than the current internal length. The second
form always updates the internal offset and length.
buffer
+
length
−
Preallocated byte array for datagram packet data
offset
Location in
buffer
where first byte is to be accessed
length
Number of bytes to be read from/written into
buffer
2.3.2 UDP Client
A UDP client begins by sending a datagram to a server that is passively waiting to be contacted.
The typical UDP client goes through three steps:
1. Construct an instance of
DatagramSocket
, optionally specifying the local address and port.
2. Communicate by sending and receiving instances of
DatagramPacket
using the
send()
and
receive()
methods of
DatagramSocket
.
3. When finished, deallocate the socket using the
close()
method of
DatagramSocket
.
Unlike a
Socket
,a
DatagramSocket
is not constructed with a specific destination address.
This illustrates one of the major differences between TCP and UDP. A TCP socket is required to
establish a connection with another TCP socket on a specific host and port before any data can
be exchanged, and, thereafter, it
only
communicates with that socket until it is closed. A UDP
socket, on the other hand, is not required to establish a connection before communication, and
each datagram can be sent to or received from a different destination. (The
connect()
method
of
DatagramSocket
does allow the specification of the remote address and port, but its use is
optional.)
Our UDP echo client,
UDPEchoClientTimeout.java
, sends a datagram containing the string
to be echoed and prints whatever it receives back from the server. A UDP echo server simply
repeats each datagram that it receives back to the client. Of course, a UDP client only commu-
nicates with a UDP server. Many systems include a UDP echo server for debugging and testing
purposes.
One consequence of using UDP is that datagrams can be lost. In the case of our echo
protocol, either the echo request from the client or the echo reply from the server may be
lost in the network. Recall that our TCP echo client sends an echo string and then blocks on
read()
waiting for a reply. If we try the same strategy with our UDP echo client and the echo
request datagram is lost, our client will block forever on
receive()
. To avoid this problem, our
client specifies a maximum amount of time to block on
receive()
, after which it tries again by
resending the echo request datagram. Our echo client performs the following steps:
Search WWH ::
Custom Search