public class PlainNio2EchoServer{ public void serve(int port)throws IOExcetpion{ System.out.println("listening for connection on port "+port); final AsychronousServerSocketChannel serverChannel = AsychronousServerSocketChannel.open(); InetAddress address = new InetAddress(port); serverChannel.bind(address); final CountDownLatch latch = new CountDownLatch(1); serverChannel.accept(null, new CompletionHandler<AsychronousSocketChannel,Object>(){ @Override public void completed(AsychronousSocketChannel channel,Object attachment){ serverChannel.accept(null,this); ByteBuffer buffer = ByteBuffer.allocate(100); channel.read(buffer,buffer,new EchoCompletionHandler(channel)); } @Override public void failed(Throwable throwable,Object attachment){ try{ serverChannel.close(); }catch(IOExcetpion ex){ }finally{ latch.countDown(); } } }); try{ latch.await(); }catch(InterruptedException ex){ Thread.currentThread().interrupt(); } } private final class EchoCompletionHandler implements CompletionHandler<Integer,ByteBuffer>{ private AsychronousSocketChannel channel; public EchoCompletionHandler(AsychronousSocketChannel channel){ this.channel = channel; } @Override public void completed(Integer result,ByteBuffer buffer){ buffer,flip(); channel.write(buffer,buffer, new CompletionHandler<Integer,ByteBuffer>{ @Override public void completed(Integer result,ByteBuffer buffer){ if(buffer.hasRemaining()){ channel.write(buffer,buffer,this); }else{ buffer.compact(); channel.read(buffer,buffer,EchoCompletionHandler.this); } } @Override public void failed(Throwable throwable,ByteBuffer attachment){ try{ channel.close(); }catch(IOExcetpion ex){ } } }); } @Override public void failed(Throwable throwable,ByteBuffer attachment){ try{ channel.close(); }catch(IOExcetpion ex){ } } } }
该代码段 出自于第五版书中英文版第一章。
第一,代码实际表述的跟我们理解的异步IO是一样的,表述不一样而已。
该段代码的解读工作其实最主要的是2个方法的理解。
1, serverChannel.accept(null,new CompletionHanlder<AsynchronousSocketChannel>{...})
2, channel.read/write(buffer,buffer, new CompletionHandler<Integer,ByteBuffer>{...})
异步IO的特点是信号驱动,比如severChannle accepte 新的connection ,那么执行的回调函数就是类CompletionHandler 中的completed()函数。accepte(..)函数是系统调用