A Generic Multithreaded Server
Example 5-10
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 its actions (to a stream, or, in Java
1.4, to a Logger) and limits the number of concurrent connections to a
specified maximum.
The Server
class uses
a number of inner classes. The Server.Listener
class is a thread that waits
for connections on a given port. There is one Listener
object for each service the
Server
is providing. The Server.ConnectionManager
class manages the
list of current connections to all services. There is one ConnectionManager
shared by all services.
When a Listener
gets a connection
from a client, it passes it to the ConnectionManager
, which rejects it if the
connection limit has been reached. If the ConnectionManager
doesn’t reject a client,
it creates a Server.Connection
object to handle the connection. Connection
is a Thread
subclass, so each service can handle
multiple connections at a time, making this a multithreaded server.
Each Connection
object is passed a
Service
object and invokes its
serve( )
method, which is what
actually provides the service.
The Service
interface
is a nested member of the Server ...
Get Java Examples in a Nutshell, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.