Java Reference
In-Depth Information
Thread
receiver
=
new
ReceiverThread
(
socket
);
receiver
.
start
();
}
catch
(
UnknownHostException
ex
)
{
System
.
err
.
println
(
ex
);
}
catch
(
SocketException
ex
)
{
System
.
err
.
println
(
ex
);
}
}
}
The
SenderThread
class reads input from the console a line at a time and sends it to the
echo server. It's shown in
Example 12-13
. The input is provided by
System.in
, but a
different client could include an option to read input from a different stream—perhaps
opening a
FileInputStream
to read from a file. The fields of this class define the server
to which it sends data, the port on that server, and the
DatagramSocket
that does the
sending, all set in the single constructor. The
DatagramSocket
is connected to the remote
server to make sure all datagrams received were in fact sent by the right server. It's rather
unlikely that some other server on the Internet is going to bombard this particular port
with extraneous data, so this is not a big flaw. However, it's a good habit to make sure
that the packets you receive come from the right place, especially if security is a concern.
The
run()
method processes user input a line at a time. To do this, the
BufferedRead
er
userInput
is chained to
System.in
. An infinite loop reads lines of user input. Each
line is stored in
theLine
. A period on a line by itself signals the end of user input and
breaks out of the loop. Otherwise, the bytes of data are stored in the data array using
the
getBytes()
method from
java.lang.String
. Next, the data array is placed in the
payload part of the
DatagramPacket
output
, along with information about the server,
the port, and the data length. This packet is then sent to its destination by
socket
. This
thread then yields to give other threads an opportunity to run.
Example 12-13. The SenderThread class
import
java.io.*
;
import
java.net.*
;
class
SenderThread
extends
Thread
{
private
InetAddress
server
;
private
DatagramSocket
socket
;
private
int
port
;
private
volatile
boolean
stopped
=
false
;
SenderThread
(
DatagramSocket
socket
,
InetAddress
address
,
int
port
)
{
this
.
server
=
address
;
this
.
port
=
port
;
this
.
socket
=
socket
;
this
.
socket
.
connect
(
server
,
port
);
}