Java Reference
In-Depth Information
Display 19.6
Date and Time Client
(part 2 of 2)
29
catch
(IOException e)
30 {
31 System.out.println(e.getMessage());
32 }
33 }
34 }
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 2006
Output when client program connects to the server program in Display 19.5.
Sockets and Threading
If you run the program in Display 19.5 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 wait-
ing 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 con-
nections while another thread handles an existing connection. Section 19.1 describes
how to create threads and make a GUI program responsive. For 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 Project 7 and 8.