Java Reference
In-Depth Information
private
volatile
boolean
stopped
=
false
;
ReceiverThread
(
DatagramSocket
socket
)
{
this
.
socket
=
socket
;
}
public
void
halt
()
{
this
.
stopped
=
true
;
}
@Override
public
void
run
()
{
byte
[]
buffer
=
new
byte
[
65507
];
while
(
true
)
{
if
(
stopped
)
return
;
DatagramPacket
dp
=
new
DatagramPacket
(
buffer
,
buffer
.
length
);
try
{
socket
.
receive
(
dp
);
String
s
=
new
String
(
dp
.
getData
(),
0
,
dp
.
getLength
(),
"UTF-8"
);
System
.
out
.
println
(
s
);
Thread
.
yield
();
}
catch
(
IOException
ex
)
{
System
.
err
.
println
(
ex
);
}
}
}
}
You can run the echo client on one machine and connect to the echo server on a second
machine to verify that the network is functioning properly between them.
DatagramChannel
The
DatagramChannel
class is used for nonblocking UDP applications, in the same way
as
SocketChannel
and
ServerSocketChannel
are used for nonblocking TCP applica‐
tions. Like
SocketChannel
and
ServerSocketChannel
,
DatagramChannel
is a subclass
of
SelectableChannel
that can be registered with a
Selector
. This is useful in servers
where one thread can manage communications with multiple clients. However, UDP is
by its nature much more asynchronous than TCP so the net effect is smaller. In UDP, a
single datagram socket can process requests from multiple clients for both input and
output. What the
DatagramChannel
class adds is the ability to do this in a nonblocking
fashion, so methods return quickly if the network isn't immediately ready to receive or
send data.
Using DatagramChannel
DatagramChannel
is a near-complete alternate API for UDP. In Java 6 and earlier, you
still need to use the
DatagramSocket
class to bind a channel to a port. However, you do