References: Time Geeks Fu Jian teacher "Netty source code analysis and practical" Talk is cheap.show me the code!
---- lines:
And also there are two threads started as completed, BOSS and the Thread worker thread;
boss thread:
①NioEventLoop the polling selector to create a connection event (OP_ACCEPT)
② create a socket channel
③ initialization socket channel and from worker selects one of NioEventLoop group
worker thread:
④ the socket channel registered to the selector selected NioEventLoop
⑤ registered read event (OP_READ) to a selector
---- source explained:
NioEventLoop found in the run (); processSelectedKeys have the run () inside ();
After point into
Wherein processSelectedKeysOptimized (); without the jdk selector.selectedKeys (), better performance, less garbage collection; then with the inside;
Marked with a breakpoint, the place to start polling the event. Then start the debug server and client (code reference https://www.cnblogs.com/-qilin/p/11671763.html )!
The method then proceeds, and then sequentially performed;
Wherein 16 represents the OP_ACCEPT; enter unsafe.read () has such a code.
Followed into doReadMessages (); the SocketChannel CH = SocketUtils.accept (javaChannel ()); acceptance of a new connection created the SocketChannel;
Then go talk to
FIG breakpoint on return serverSocketChannel.accept (); represents a non-blocking mode, or null when there is no connection request; then will continue to go down to the place:
pipeline.fireChannelRead (readBuf.get (i)); it can be seen that a plurality Handler, then find the ServerBootstrapAcceptor Handler, then find channelRead () method to make a break skipped:
Further down childGroup.register (child) .addListener (); plus a break with the inside:
Then follow step by step follow-up after the register () and later to the code below, make a break:
Enter register0 ()
See the familiar doRegister (), with the inside look:
Here and articles on the same source explained, continue to go down:
On the jump to head, find the read () method:
Then go in and see
We see the familiar doBeginRead (); now look into
The difference is not 16 but this time readInterestOp 1, and is OP_READ rather than a OP_ACCEPT. This time to have run. You can see the console:
----to sum up:
Essence received connection:
selector.select () / selectNow () / select (timeoutMillis) found OP_ACCEPT event processing:
SocketChannel socketChannel = serverSocketChannel.accopt();
selectionKey = javaChannel().register(eventLoop().unwrappedSelector(),0,this);
selectKey.interestOps(OP_READ);
创建连接的初始化和注册是通过pipeline.fireChannelRead在ServerBootstrapAcceptor中完成的。
第一次Register并不是监听OP_READ,而是0;
selectionKey = javaChannel().register(eventLoop().unwrappedSelector(),0,this);
最终监听OP_READ是通过“Register”完成后的fireChannelActive(io.netty.channel.AbstractChannel.AbstractUnsafe#register0中)来触发的;
Worker's NioEventLoop是通过Register操作执行来启动。
接受连接的读操作,不会尝试读取更多次(16次)。