Handling Multiple Clients
Problem
Your server needs to handle multiple clients.
Solution
Use a thread for each.
Discussion
In the C world, there are several mechanisms that allow a server to
handle multiple clients. One is to use a special system call
select( )
or poll( )
, which
notifies the server when any of a set of file/socket descriptors is
ready to read, ready to write, or has an error. By including its
rendezvous socket (equivalent to our
ServerSocket
) in this list, the C-based server can
read from any of a number of clients in any order. Java does not
provide this call, as it is not readily implementable on some Java
platforms. Instead, Java uses the general-purpose
Thread
mechanism, as described in Section 24.9. Threads are, in fact, one of the other
mechanisms available to the C programmer on most platforms. Each time
the code accepts a new connection from the
ServerSocket
, it immediately constructs and starts
a new thread object to process that client.[38]
The code to implement accepting on a
socket is pretty
simple, apart from having to catch IOException
s:
/** Run the main loop of the Server. */ void runServer( ) { while (true) { try { Socket clntSock = sock.accept( ); new Handler(clntSock).start( ); } catch(IOException e) { System.err.println(e); } } }
To use a thread,
you must either subclass Thread
or implement
Runnable
. The
Handler
class must be a subclass of
Thread
for this code to work as written; if
Handler
instead implemented the
Runnable
interface, the code would ...
Get Java Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.