Java Reference
In-Depth Information
Before J2SE 1.4, there was no specifi c provision for non-blocking I/O in Java,
so the multithreaded option was the only feasible one for Java programmers.
The introduction of non-blocking I/O in 1.4 was a major advance for Java network
programmers and will be covered in the latter part of this chapter. For the time
being, though, we shall restrict our attention to the more long-standing (and still
widely used) implementation of servers via multithreading.
Though inferior to the non-blocking approach, the multithreaded technique has a
couple of signifi cant benefi ts:
￿ it offers a 'clean' implementation, by separating the task of allocating connec-
tions from that of processing each connection;
it is robust, since a problem with one connection will not affect other connections.
The basic technique involves a two-stage process:
1. the main thread (the one running automatically in method main ) allocates indi-
vidual threads to incoming clients;
2. the thread allocated to each individual client then handles all subsequent interac-
tion between that client and the server (via the thread's run method).
Since each thread is responsible for handling all further dialogue with its particu-
lar client, the main thread can 'forget' about the client once a thread has been
allocated to it. It can then concentrate on its simple tasks of waiting for clients to
make connection and allocating threads to them as they do so. For each client-
handling thread that is created, of course, the main thread must ensure that the
client-handling thread is passed a reference to the socket that was opened for the
associated client.
The separation of responsibilities means that, if a problem occurs with the con-
nection to a particular client, it has no effect on the connections to other clients and
there is no general loss of service. This is a major benefi t, of course.
This is another echo server implementation, but one that uses multithreading to return
messages to multiple clients. It makes use of a support class called ClientHandler that
extends class Thread . Whenever a new client makes connection, a ClientHandler
thread is created to handle all subsequent communication with that particular client.
When the ClientHandler thread is created, its constructor is supplied with a reference
to the relevant socket.
Here's the code for the server…
public class MultiEchoServer
private static ServerSocket serverSocket;
private static fi nal int PORT = 1234;
Search WWH ::

Custom Search