O'Reilly logo

Java Examples in a Nutshell, 3rd Edition by David Flanagan

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required