Java Reference
In-Depth Information
Display 19.8
Date and Time Client (part 2 of 2)
29 catch (IOException e)
30 {
31 System.out.println(e.getMessage());
32 }
33 }
34 }
Output when client program connects to the server program in Display 19.7.
Sample Dialogue
Connecting to server on port 7654
Connection made, sending name.
Waiting for reply.
Received: Welcome, Dusty Rhodes, Today is Fri Oct 13 03:03:21 AKDT 2011
Note that the socket and stream objects throw checked exceptions. This means that
their exceptions must be caught or declared in a throws block.
Sockets and Threading
If you run the program in Display 19.7, then you will notice that the server waits,
or blocks , at the serverSock.accept( ) call until a client connects to it. Both the
client and server also block at the readLine( ) call if data from the socket is not yet
available. In a client with a GUI, you would notice this as a nonresponsive program
while it is waiting for data. For the server, this behavior makes it difficult to handle
connections with more than one client. After a connection is made with the first
client, the server will become nonresponsive to the client's requests while it waits for a
second client.
The solution to this problem is to use threads. One thread will listen for new
connections while another thread handles an existing connection. Section 19.1
describes how to create threads and make a GUI program responsive. On the server,
the accept( ) call is typically placed in a loop and a new thread is created to handle
each client connection:
blocking
while ( true )
{
Socket connectionSock = serverSock.accept( );
ClientHandler handler = new ClientHandler(connectionSock);
Thread theThread = new Thread(handler);
theThread.start( );
}
In this code, ClientHandler is a class that implements Runnable . The constructor
keeps a reference to the socket in an instance variable, and the run( ) method would
handle all communications. A complete implementation of a threaded server is left as
Programming Projects 19.7 and 19.8.
 
 
Search WWH ::




Custom Search