快速业务通道

Java AIO初探(异步网络IO) - 编程入门网

作者 佚名技术 来源 NET编程 浏览 发布时间 2012-06-21
mpleted方法中在最后都调用了pendingAccept来继续发起accept调用,等待新的连接上来。有的同学可能要说了,这样搞是不是递归调用,会不会堆栈溢出?实际上不会,因为发起accept调用的线程与CompletionHandler回调的线程并非同一个,不是一个上下文中,两者之间没有耦合关系。要注意到,CompletionHandler的回调共用的是 AsynchronousChannelGroup绑定的线程池,因此千万别在回调方法中调用阻塞或者长时间的操作,例如sleep,回调方法最好能支持超时,防止线程池耗尽。

连接建立后,怎么读和写呢?回忆下在nonblocking nio框架中,连接建立后的第一件事是干什么?注册OP_READ事件等待socket可读。异步IO也同样如此,连接建立后马上发起一个异步read调用,等待socket可读,这个是Session.start方法中所做的事情:

public class AioTCPSession {    protected void start0() {        pendingRead();    }    protected final void pendingRead() {        if (!isClosed() && this.asynchronousSocketChannel.isOpen()) {            if (!this.readBuffer.hasRemaining()) {                this.readBuffer = ByteBufferUtils                        .increaseBufferCapatity(this.readBuffer);            }            this.readFuture = this.asynchronousSocketChannel.read(                    this.readBuffer, this, this.readCompletionHandler);        } else {            throw new IllegalStateException(                    "Session Or Channel has been closed");        }    }   }

AsynchronousSocketChannel的read调用与AsynchronousServerSocketChannel的accept调用类似,同样是非阻塞的,返回结果也是一个Future,但是写的结果是整数,表示写入了多少字节,因此read调用返回的是 Future<Integer>,方法的第一个参数是读的缓冲区,操作系统将IO读到数据拷贝到这个缓冲区,第二个参数是传递给 CompletionHandler的attchment,第三个参数就是注册的用于回调的CompletionHandler。这里保存了read的结果Future,这是为了在关闭连接的时候能够主动取消调用,accept也是如此。现在可以看看read的CompletionHandler的实现:

public final class ReadCompletionHandler implements          CompletionHandler<Integer, AbstractAioSession> {      private static final Logger log = LoggerFactory              .getLogger(ReadCompletionHandler.class);      protected final AioTCPController controller;      public ReadCompletionHandler(AioTCPController controller) {          this.controller = controller;      }      @Override      public void cancelled(AbstractAioSession session) {          log.warn("Session(" + session.getRemoteSocketAddress()                  + ") read operation was canceled");      }      @Override      public void completed(Integer result, AbstractAioSession session) {          if (log.isDebugEnabled())              log.debug("Session(" + session.getRemoteSocketAddress()      

凌众科技专业提供服务器租用、服务器托管、企业邮局、虚拟主机等服务,公司网站:http://www.lingzhong.cn 为了给广大客户了解更多的技术信息,本技术文章收集来源于网络,凌众科技尊重文章作者的版权,如果有涉及你的版权有必要删除你的文章,请和我们联系。以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢!

分享到: 更多

Copyright ©1999-2011 厦门凌众科技有限公司 厦门优通互联科技开发有限公司 All rights reserved

地址(ADD):厦门软件园二期望海路63号701E(东南融通旁) 邮编(ZIP):361008

电话:0592-5908028 传真:0592-5908039 咨询信箱:web@lingzhong.cn 咨询OICQ:173723134

《中华人民共和国增值电信业务经营许可证》闽B2-20100024  ICP备案:闽ICP备05037997号