A Robust, Interruptible Server
Our next program (Code Example 17-6) is a variation of our old friend the producer/consumer
version of a network server. In this version of it, we show how we can use
InterruptedException to shut down the server on demand as we did in our StopQueue
example. The main distinction between this program and StopQueue is that this version will not
only interrupt the threads waiting on sockets, but it will also handle any of the checked exceptions
no matter what the client code is doing.
Note that we do close the socket as soon as we get the InterruptedException because it may
not be in a recoverable state.
Example 17-6 A Robust Server
A simple server program. It sets up a TCP port for the client
program to connect to. Then it accepts connections, spawning a
new producer thread for each. [Java has no "select()" function.]
It starts up nConsumers consumer threads to pull requests off the
list and process them, sending a reply string back to the client.
Any IO failures are handled by printing out an error message,
the socket in question, then ignoring it. Check out the location
the exception handlers and which methods throw exceptions. This is
carefully designed and *should* be fully robust.
This version is really just a producer/consumer program that
to run across a socket.
Unlike the StopQueueSolution, which has the consumer threads exit
stop time (that was done for the illustration of synchronization),
program simply stops accepting new requests, closing the socket as
as the final reply has been issued. The Client program is sent an
message then, and left to its own devices to deal with the fact
socket has been closed.
This program uses InterruptedIOException, hence MUST be compiled
Search WWH :