Handling Multiple Clients


while (true) {     Socket clientSock = socket.accept();     new Handler(clientSock).start(); }



To handle multiple clients, we create a thread for each incoming request that we are processing.

In this phrase, we create a new thread to handle the incoming client connection immediately after accepting the connection. This frees our server listener thread to continue listening for other client connections. In the phrase, we are in an infinite while loop so that after a thread is spawned to handle an incoming request, the server immediately goes back to waiting for another request. The Handler class that we use to start the thread from must be a subclass of the THRead class, or it must implement the Runnable interface. The code used in the phrase would be correct if the Handler class is a subclass of the THRead class. If the Handler class instead implements the Runnable interface, the thread start code would change to the following:

Thread thd = new Thread(new Handler(clientSock)); thd.start();


An example of a simple Handler class extending the Thread class is shown here:

class Handler extends Thread {    Socket sock;    Handler(Socket socket) {       this.sock = socket;    }    public void run() {       DataInputStream in =          new DataInputStream(sock.getInputStream());       PrintStream out =          new PrintStream(sock.getOutputStream(),                true);       // handle client request       sock.close();    } }


This class could be used to handle incoming client requests. We don't show the details of handling a specific request in the code. When the start() method of this class is called, as in our phrase, the run() method that we have defined is executed. The start() method is implemented in the Thread base class, and we do not have to override that in our Handler implementation.

When creating a multi-threaded solution such as we've outlined in this phrase, you might also want to consider using thread pooling. With a thread pool, rather than creating a new thread for each incoming request, a pool of threads is created at application start time. The thread pool has a fixed number of threads that execute tasks. Using a thread pool will prevent the application from creating an excessive number of threads which could impede performance. A very good article describing thread pooling is available from http://www.informit.com/articles/article.asp?p=30483&seqNum=3&rl=1

For more information about using threads, see Chapter 15, "Using Threads."




JavaT Phrasebook. Essential Code and Commands
Java Phrasebook
ISBN: 0672329077
EAN: 2147483647
Year: 2004
Pages: 166

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net