netty介绍:服务端启动

背景

我们一个服务端的程序,启动的时候就可以做两个事情: 一是绑定本地地址,二是监听端口

简单版本

监听

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中的成员,我们看他是在哪里赋值的

你可能感兴趣的:(netty介绍:服务端启动)