Handling Multiple Clients


Your server needs to handle multiple clients.


Use a thread for each.


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 IOExceptions:

/** Run the main loop of the Server. */
void runServer(  ) {
    while (true) {
        try {
            Socket clntSock = sock.accept(  );
            new Handler(clntSock).start(  );
        } catch(IOException 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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.