Java Reference
In-Depth Information
Connecting to a remote server a couple of miles and seven hops away (according to
traceroute), I saw between 90% and 98% of the packets make the round trip.
Closing
Just as with regular datagram sockets, a channel should be closed when you're done with
it to free up the port and any other resources it may be using:
public
void
close
()
throws
IOException
Closing an already closed channel has no effect. Attempting to write data to or read data
from a closed channel throws an exception. If you're uncertain whether a channel has
been closed, check with
isOpen()
:
public
boolean
isOpen
()
This returns
false
if the channel is closed,
true
if it's open.
Like all channels, in Java 7
DatagramChannel
implements
AutoCloseable
so you can
use it in try-with-resources statements. Prior to Java 7, close it in a
finally
block if you
can. By now the pattern should be quite familiar. In Java 6 and earlier:
DatagramChannel
channel
=
null
;
try
{
channel
=
DatagramChannel
.
open
();
// Use the channel...
}
catch
(
IOException
ex
)
{
// handle exceptions...
}
finally
{
if
(
channel
!=
null
)
{
try
{
channel
.
close
();
}
catch
(
IOException
ex
)
{
// ignore
}
}
}
and in Java 7 and later:
try
(
DatagramChannel
channel
=
DatagramChannel
.
open
())
{
// Use the channel...
}
catch
(
IOException
ex
)
{
// handle exceptions...
}
Socket Options // Java 7
In Java 7 and later,
DatagramChannel
supports eight socket options listed in
Table 12-1
.