A Multiplexed Server

Example 6-13 is a simple server named PrintServiceWebInterface that responds to HTTP GET requests by sending an HTML document describing available printers. The server obtains information about printers using the javax.print package, which we’ll see again in Chapter 13.

More important than the printer-information details is the structure of this example: it is a simple single-threaded server, multiplexed using a Selector object so that it can handle requests from multiple clients concurrently. The code is well-commented and should be easy to understand. The Selector monitors the ServerSocketChannel used to accept client connections and also monitors any SocketChannel objects that represent currently active clients. When a new connection is accepted, the new SocketChannel is registered with the Selector. When that channel becomes readable, the server reads the client’s request (in this case it ignores the details of the request), sends a response, and then (in this case, since HTTP is a stateless protocol) closes SocketChannel and cancels its registration with the Selector so that it will no longer be monitored. This basic architecture is adaptable to a variety of server implementations.

One interesting feature of this class is that it uses the write( ) method of the GatheringByteChannel interface. This method takes an array of ByteBuffer objects and writes their contents sequentially, which allows us to separate the fixed content of the HTTP headers from the ...

Get Java Examples in a Nutshell, 3rd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.