netty源码分析之--新连接接入过程
2018-07-11 本文已影响0人
shoulda
netty是在哪里检测有新连接接入的
新连接是怎么注册到NioEventLoop线程中的
Netty新连接接入处理逻辑
1.检测新连接
2.创建NioSocketChannel
3.分配线程及注册selector
4.向selector注册读事件
1.新连接检测
//检测连接
private void processSelectedKey(SelectionKey k, AbstractNioChannel ch) {
NioUnsafe unsafe = ch.unsafe();
if (!k.isValid()) {
NioEventLoop eventLoop;
try {
eventLoop = ch.eventLoop();
} catch (Throwable var6) {
return;
}
if (eventLoop == this && eventLoop != null) {
unsafe.close(unsafe.voidPromise());
}
} else {
try {
int readyOps = k.readyOps();
if ((readyOps & 8) != 0) {
int ops = k.interestOps();
ops &= -9;
k.interestOps(ops);
unsafe.finishConnect();
}
if ((readyOps & 4) != 0) {
ch.unsafe().forceFlush();
}
if ((readyOps & 17) != 0 || readyOps == 0) {
unsafe.read();
if (!ch.isOpen()) {
return;
}
}
} catch (CancelledKeyException var7) {
unsafe.close(unsafe.voidPromise());
}
}
}
2.创建NioSocketChannel
new NioSocketChannel(parent,ch):入口
AbstractNioByteChannel(p,ch,op_read)
configureBlocking(false)&save op
create id,unsafe,pipeline
new NioSockectChannelConfig()
setTcpNoDelay(true):禁止Nagle算法
2.1 Netty中的Channel的分类
NioServerSocketChannel
NioSocketChannel
Unsafe
2.2 Netty中channel层级关系
image.png3新连接NioEventLoop分配和selector注册
3.1服务端Channel的pipeline构成
image.png3.2ServerBootstrapAcceptor的功能
1.添加childHandler
2.设置options和attrs
3.选择NioEventLoop并注册selector
4.向selector注册读事件(NioSocketChannel读事件的注册)
通过传播channelactive方法,将客户端的读时间注册到selector