Netty 新连接的接入
2018-11-28 本文已影响28人
良辰美景TT
本文通过源码分析Netty是如何一步步的将接收客户端的新连接,然后将连跟NioEventLoop绑定,并注册相应的Read事件。
检测新连接
-
入口为NioEventLoop的processSelectedKey方法
新连接接入的入口
-
进入到NioMessageUnsafe的read方法
NioMessageUnsafe的read方法
-
doReadMessages里会接收连接,封装成netty里的NioSocketChannel对象
NioServerSocketChannel类里的doReadMessages
创建NioSocketChannel
Netty通过new 关键字直接创建NioSocketChannel。主要做了如下几步:
-
调用AbstractNioByteChannel,传入通过accept接收的底层channel。
AbstractNioByteChannel构造方法
-
通过AbstractNioChannel设置channel的blocking属性为false。
AbstractNioChannel构造方法
-
继续调用父类,构造channel的id, unsafe与pipeline对象。
AbstractChannel构造方法
-
构造NioSocketChannelConfig对象,并通过config对象设置tcpNoDelay为true来禁止Nagle算法
NioSocketChannelConfig构造方法
Nagle算法设置为false
分配线程及注册selector
在接收完连接,并封装成NioSocketChannel后,在NioMessageUnsafe的read方法里,通过pipeline触发channelRead事件。
之后会在ServerBootstrapAcceptor(这个handler会在服务器bind的方法里添加到NioServerSocketChannel里)这个handler里完成如下步骤
-
添加childHandler并设置options和attrs
ServerBootstrapAcceptor的channelRead方法
-
通过chooser选择完NioEventLoop后最终会调用到channel的unsafe的register方法,完成注册操作
SingleThreadEventLoop的register方法
-
绑定nioEventLoop对象,并调用register0方法
AbstractUnsafe人register方法
-
调用doRegister完成具体的注册
调用doRegister完成具体的注册
-
将channel注册到selector上
AbstractNioChannel类的doRegister方法
向selector注册读事件
将NioSocketChannel绑定到selector后,需要注册相应的I/O事件,这样channel就能通过事件响应业务请求了,chennel注册读事件的流程比较长,最终会调用到AbstractUnsafe类的beginRead方法里:
-
最终会调用到AbstractNioChannel的doBeginRead方法里
AbstractNioChannel的doBeginRead方法