Java Reference
In-Depth Information
public
void
halt
()
{
this
.
stopped
=
true
;
}
@Override
public
void
run
()
{
try
{
BufferedReader
userInput
=
new
BufferedReader
(
new
InputStreamReader
(
System
.
in
));
while
(
true
)
{
if
(
stopped
)
return
;
String
theLine
=
userInput
.
readLine
();
if
(
theLine
.
equals
(
"."
))
break
;
byte
[]
data
=
theLine
.
getBytes
(
"UTF-8"
);
DatagramPacket
output
=
new
DatagramPacket
(
data
,
data
.
length
,
server
,
port
);
socket
.
send
(
output
);
Thread
.
yield
();
}
}
catch
(
IOException
ex
)
{
System
.
err
.
println
(
ex
);
}
}
}
The
ReceiverThread
class shown in
Example 12-14
waits for datagrams to arrive from
the network. When a datagram is received, it is converted to a
String
and printed on
System.out
for display to the user. A more advanced echo client could include an option
to send the output elsewhere.
This class has two fields. The more important is the
DatagramSocket
,
theSocket
, which
must be the same
DatagramSocket
used by the
SenderThread
. Data arrives on the port
used by that
DatagramSocket
; any other
DatagramSocket
would not be allowed to con‐
nect to the same port. The second field,
stopped
, is a boolean used to halt this thread
without invoking the deprecated
stop()
method.
The
run()
method is an infinite loop that uses
socket
's
receive()
method to wait for
incoming datagrams. When an incoming datagram appears, it is converted into a
String
with the same length as the incoming data and printed on
System.out
. As in the input
thread, this thread then yields to give other threads an opportunity to execute.
Example 12-14. The ReceiverThread class
import
java.io.*
;
import
java.net.*
;
class
ReceiverThread
extends
Thread
{
private
DatagramSocket
socket
;