Java Reference
In-Depth Information
Example 5•8: GenericClient.java (continued)
to_user.flush();
}
}
catch (IOException e) { to_user.println(e); }
// When the server closes the connection, the loop above
// will end. Tell the user what happened, and call
// System.exit(), causing the main thread to exit along
// with this one.
to_user.println("Connection closed by server.");
System.exit(0);
}
};
// We set the priority of the server-to-user thread above to be
// one level higher than the main thread. We shouldn't have to do
// this, but on some operating systems, output sent to the console
// doesn't appear when a thread at the same priority level is
// blocked waiting for input from the console.
t.setPriority(Thread.currentThread().getPriority() + 1);
// Now start the server-to-user thread
t.start();
// In parallel, read the user's input and pass it on to the server.
String line;
while((line = from_user.readLine()) != null) {
to_server.print(line + "\n");
to_server.flush();
}
// If the user types a Ctrl-D (Unix) or Ctrl-Z (Windows) to end
// their input, we'll get an EOF, and the loop above will exit.
// When this happens, we stop the server-to-user thread and close
// the socket.
s.close();
to_user.println("Connection closed by client.");
System.exit(0);
}
// If anything goes wrong, print an error message
catch (Exception e) {
System.err.println(e);
System.err.println("Usage: java GenericClient <hostname> <port>");
}
}
}
A Generic Multithreaded Server
Example 5-9 is a long and fairly complex example. The Server class it defines is a
multithreaded server that provides services defined by implementations of a nested
Server.Service interface. It can provide multiple services (defined by multiple
Service objects) on multiple ports, and it has the ability to dynamically load and
instantiate Service classes and add (and remove) new services at runtime. It logs
Search WWH ::




Custom Search