Java Reference
In-Depth Information
}
}
A UDP Echo Client
The UDPPoke class implemented earlier isn't suitable for all protocols. In particular, pro‐
tocols that require multiple datagrams require a different implementation. The echo
protocol has both TCP and UDP implementations. Implementing the echo protocol
with TCP is simple; it's more complex with UDP because you don't have I/O streams or
the concept of a connection to work with. A TCP-based echo client can send a message
and wait for a response on the same connection. However, a UDP-based echo client has
no guarantee that the message it sent was received. Therefore, it cannot simply wait for
the response; it needs to be prepared to send and receive data asynchronously.
This behavior is fairly simple to implement using threads, however. One thread can
process user input and send it to the echo server, while a second thread accepts input
from the server and displays it to the user. The client is divided into three classes: the
main UDPEchoClient class, the SenderThread class, and the ReceiverThread class.
The UDPEchoClient class should look familiar. It reads a hostname from the command
line and converts it to an InetAddress object. UDPEchoClient uses this object and the
default echo port to construct a SenderThread object. This constructor can throw a
SocketException , so the exception must be caught. Then the SenderThread starts. The
same DatagramSocket that the SenderThread uses is used to construct a ReceiverTh
read , which is then started. It's important to use the same DatagramSocket for both
sending and receiving data because the echo server will send the response back to the
port the data was sent from. Example 12-12 shows the code for the UDPEchoClient .
Example 12-12. The UDPEchoClient class
import java.net.* ;
public class UDPEchoClient {
public final static int PORT = 7 ;
public static void main ( String [] args ) {
String hostname = "localhost" ;
if ( args . length > 0 ) {
hostname = args [ 0 ];
}
try {
InetAddress ia = InetAddress . getByName ( hostname );
DatagramSocket socket = new DatagramSocket ();
SenderThread sender = new SenderThread ( socket , ia , PORT );
sender . start ();
Search WWH ::




Custom Search