加入收藏 | 设为首页 | 会员中心 | 我要投稿 西安站长网 (https://www.029zz.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 业界 > 正文

查漏补缺:连接器在Tomcat中是如何设计的

发布时间:2019-09-25 12:20:52 所属栏目:业界 来源:今日头条
导读:副标题#e# 从连接器(Connector)源码说起 既然是来解析连接器(Connector),那么我们直接从源码入手,后面所有源码我会剔除不重要部分,所以会忽略大部分源码细节,只关注流程。源码如下(高能预警,大量代码): publicclassConnectorextendsLifecycleMBeanBas

这里可以发现Acceptor主要就是接受socket,然后把它注册到poller中,我们继续看看是如何注册的。

  1. /**6.类NioEndpoint 
  2.  * Registers a newly created socket with the poller. 
  3.  * 
  4.  * @param socket The newly created socket 
  5.  * @param socketWrapper The socket wrapper 
  6.  */ 
  7.  public void register(final NioChannel socket, final NioSocketWrapper socketWrapper) { 
  8.  socketWrapper.interestOps(SelectionKey.OP_READ);//this is what OP_REGISTER turns into. 
  9.  PollerEvent r = null; 
  10.  if (eventCache != null) { 
  11.  r = eventCache.pop(); 
  12.  } 
  13.  if (r == null) { 
  14.  r = new PollerEvent(socket, OP_REGISTER); 
  15.  } else { 
  16.  r.reset(socket, OP_REGISTER); 
  17.  } 
  18.  addEvent(r); 
  19.  } 
  20. /** 7.类:PollerEvent implements Runnable 
  21.  public void run() { 
  22.  //省略部分代码 
  23.  socket.getIOChannel().register(socket.getSocketWrapper().getPoller().getSelector(), SelectionKey.OP_READ, socket.getSocketWrapper()); 
  24.  } 

这里发现最终就是采用NIO模型把其注册到通道中。(这里涉及NIO网络编程知识,不了解的同学可以传送这里)。那么注册完毕后,我们看看Poller做了什么事情。

  1. */  
  2.  /**8.类:NioEndPoint内部类 Poller implements Runnable 
  3.  **/  
  4.  @Override 
  5.  public void run() { 
  6.  // Loop until destroy() is called 
  7.  while (true) { 
  8.  //省略部分代码 
  9.  Iterator<SelectionKey> iterator = 
  10.  keyCount > 0 ? selector.selectedKeys().iterator() : null; 
  11.  // Walk through the collection of ready keys and dispatch 
  12.  // any active event. 
  13.  while (iterator != null && iterator.hasNext()) { 
  14.  SelectionKey sk = iterator.next(); 
  15.  NioSocketWrapper socketWrapper = (NioSocketWrapper) sk.attachment(); 
  16.  // Attachment may be null if another thread has called 
  17.  // cancelledKey() 
  18.  if (socketWrapper == null) { 
  19.  iterator.remove(); 
  20.  } else { 
  21.  iterator.remove(); 
  22.  //sock处理 
  23.  processKey(sk, socketWrapper); 
  24.  } 
  25.  } 
  26.  //省略部分代码 
  27.  }  

(编辑:西安站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

热点阅读