Java Reference
In-Depth Information
Example 5•9: Server.java (continued)
* A Connection thread calls this method just before it exits. It removes
* the specified Connection from the set of connections.
**/
protected synchronized void endConnection(Connection c) {
connections.remove(c);
log("Connection to " + c.client.getInetAddress().getHostAddress() +
":" + c.client.getPort() + " closed.");
}
/** Change the current connection limit */
public synchronized void setMaxConnections(int max) {
maxConnections = max;
}
/**
* This method displays status information about the server on the
* specified stream. It can be used for debugging, and is used by the
* Control service later in this example.
**/
public synchronized void displayStatus(PrintWriter out) {
// Display a list of all Services that are being provided
Iterator keys = services.keySet().iterator();
while(keys.hasNext()) {
Integer port = (Integer) keys.next();
Listener listener = (Listener) services.get(port);
out.print("SERVICE " + listener.service.getClass().getName()
+ " ON PORT " + port + "\n");
}
// Display the current connection limit
out.print("MAX CONNECTIONS: " + maxConnections + "\n");
// Display a list of all current connections
Iterator conns = connections.iterator();
while(conns.hasNext()) {
Connection c = (Connection)conns.next();
out.print("CONNECTED TO " +
c.client.getInetAddress().getHostAddress() +
":" + c.client.getPort() + " ON PORT " +
c.client.getLocalPort() + " FOR SERVICE " +
c.service.getClass().getName() + "\n");
}
}
/**
* This class is a subclass of Thread that handles an individual
* connection between a client and a Service provided by this server.
* Because each such connection has a thread of its own, each Service can
* have multiple connections pending at once. Despite all the other
* threads in use, this is the key feature that makes this a
* multi-threaded server implementation.
**/
public class Connection extends Thread {
Socket client;
// The socket to talk to the client through
Service service;
// The service being provided to that client
/**
* This constructor just saves some state and calls the superclass
Search WWH ::




Custom Search