Java Reference
In-Depth Information
Handle datagram reception:
lines 33-43
receive()
blocks until it either receives a datagram or the timer expires. Timer expi-
ration is indicated by an
InterruptedIOException
. If the timer expires, we increment
the send attempt count (
tries
) and start over. After the maximum number of tries,
the while loop exits without receiving a datagram. If
receive()
succeeds, we set the
loop flag
receivedResponse
to
true
, causing the loop to exit. Since packets may come
from anywhere, we check the source address of the recieved datagram to verify that
it matches the address of the specified echo server.
7.
Print reception results:
lines 46-49
If we received a datagram,
receivedResponse
is
true
, and we can print the datagram data.
8.
Close the socket:
line 51
We invoke the UDP client using the same parameters as used in the TCP client.
DatagramSocket
Constructors
DatagramSocket
()
DatagramSocket
(
int
localPort
)
DatagramSocket
(
int
localPort
,
InetAddress
localAddr
)
Constructs a UDP socket. Either or both the local port and address may be specified.
If the local port is not specified, the socket is bound to any available local port. If the
local address is not specified, one of the local addresses is chosen.
localPort
Local port; a localPort of 0 allows the constructor to pick any
available port.
localAddr
Local address
Operators
void
close
()
After closing, datagrams may no longer be sent or received using this socket.
void
connect
(
InetAddress
remoteAddr
,
int
remotePort
)
Sets the remote address and port of the socket. Attempting to send datagrams with
a different address will cause an exception to be thrown. The socket will only receive
datagrams from the specified port and address. Datagrams from any other port or
address are ignored. This is strictly a local operation because there is no end-to-end
connection.
Caveat:
A socket that is connected to a multicast or broadcast address can
Search WWH ::
Custom Search