Java Reference
In-Depth Information
... In the main() method in MicroServer ...
// Create a ServerSocket object to watch port for clients
ServerSocket server - socket = new ServerSocket (port);
System.out.println ("Server started");
// Loop indefinitely while waiting for clients to connect
while (true) {
// accept () does not return until a client
// requests a connection
Socket client - socket = server - socket.accept ();
// Now that a client has arrived, create an instance
// of our thread subclass to respond to it.
Worker worker = new Worker (client - socket);
worker.start ();
System.out.println ( " New client connected " );
}
...
The program passes the socket to an instance of a thread class called Worker that
handles all further communication with this particular client. The main thread
loop then returns to wait for another client connection. When one arrives it will
create a new Worker to handle it. The details of the Worker class are discussed
next.
14.2.2 Worker threads for clients
Our Worker class is a subclass of Thread . There will be one Worker object
per client:
/** Here is our thread class to handle clients.**/
public class Worker extends Thread {
Socket fClient;
// Pass the socket as an argument to the constructor
Worker (Socket client) throws SocketException {
fClient = client;
// Set the thread priority down so that the
// ServerSocket will be responsive to new clients.
setPriority (MIN - PRIORITY);
} // ctor
public void run () {
... Do the client interaction here
}
...
} // class Worker
Search WWH ::




Custom Search