#1 Bind server to port
#2 Register the channel with the selector to be interested in new Client connections that get accepted
#3 Block until something is selected
#4 Get all SelectedKey instances
#5 Remove the SelectedKey from the iterator
#6 Accept the client connection
#7 Register connection to selector and set ByteBuffer
#8 Check for SelectedKey for read
#9 Read data to ByteBuffer
#10 Check for SelectedKey for write
#11 Write data from ByteBuffer to channel
This example is more complex than the previous version of EchoServer. This complexity is a
trade off; asynchronous code is typically more complicated than its synchronous counterpart.
Semantically, the original NIO and the new NIO.2 API are similar, but their implementations
are different. We!ll take a look the differences next, and we!ll implement version 3 of
EchoServer.
1.3.4 EchoServer based on NIO.2
Unlike the original NIO implementation, NIO.2 allows you to issue IO operations and provide
what is called a completion handler (
CompletionHandler class). This completion handler
gets executed after the operation completes. Therefore, execution of the completion handler is
driven by the underlying system and the implementation is hidden from the developer. It also
guarantees that only one
CompletionHandler is executed for channel at the same time. This
approach helps to simplify the code because it removes the complexity that comes with
multithreaded execution.
The major difference between the original NIO and NIO.2 is that you don!t have to check
whether an event accours on the Channel and then trigger some action. In NIO.2 you can just
trigger an IO operation and register a completion handler with it, this handler will then get
notified once the operation complates. This removes the need to create your own application
logic to check for completion, which itself results in unnecessary processing.
Now let!s see how the same asynchronous EchoServer would be implemented with
NIO2,implementation as shown in the next listing.
Listing 1.7 EchoServer v3: NIO.2
public class PlainNio2EchoServer {
public void serve(int port) throws IOException {
System.out.println("Listening for connections on port " + port);
final AsynchronousServerSocketChannel serverChannel =
AsynchronousServerSocketChannel.open();
InetSocketAddress address = new InetSocketAddress(port);
serverChannel.bind(address); #1
final CountDownLatch latch = new CountDownLatch(1);
serverChannel.accept(null, new
CompletionHandler<AsynchronousSocketChannel, Object>() { #2
@Override
public void completed(final AsynchronousSocketChannel channel,
Object attachment) {
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
http://www.manning-sandbox.com/forum.jspa?forumID=857