背景
我們一個服務端的程序,啟動的時候就可以做兩個事情: 一是綁定本地地址,二是監聽端口
簡單版本
監聽
io.netty.channel.nio.AbstractNioChannel.java
protected void doRegister() throws Exception {
boolean selected = false;
for (;;) {
try {
selectionKey = javaChannel().register(eventLoop().selector, 0, this);
return;
} catch (CancelledKeyException e) {
if (!selected) {
// Force the Selector to select now as the "canceled" SelectionKey may still be
// cached and not removed because no Select.select(..) operation was called yet.
eventLoop().selectNow();
selected = true;
} else {
// We forced a select operation on the selector before but the SelectionKey is still cached
// for whatever reason. JDK bug ?
throw e;
}
}
}
}
核心就是 selectionKey = javaChannel().register(eventLoop().selector, 0, this);
首先,javaChannel()返回的是一個SelectableChannel對象,然后注冊到當前線程的 selector,此時監聽的事件還是0(不監聽?),并且帶上了當前的對象,這個作為異步場景下數據的載體,用于數據的透傳
添加監聽的事件 (op_accept)
io.netty.channel.nio.AbstractNioChannel.java
protected void doBeginRead() throws Exception {
// Channel.read() or ChannelHandlerContext.read() was called
if (inputShutdown) {
return;
}
final SelectionKey selectionKey = this.selectionKey;
if (!selectionKey.isValid()) {
return;
}
readPending = true;
final int interestOps = selectionKey.interestOps();
if ((interestOps & readInterestOp) == 0) {
selectionKey.interestOps(interestOps | readInterestOp);
}
}
在上面的函數中,主要是看監聽的時間是否有readInterestOp,如果沒有,那么就添加上。那么這個readInterestOp值是什么呢?從這里可以看出他是AbstractNioChannel中的成員,我們看他是在哪里賦值的