Netty源码笔记I - 关于『注册SelectionKey#OP_ACCEPT』

嗯,Mina的社区不够活跃,我转投Netty了。

翻看Netty的源码有一些时间了,但卡在了一个点上,它是在哪个逻辑里面注册
SelectionKey#OP_ACCEPT的呢?经过我断断续续的努力,各种debug断点调试,
终于取得了突破。

最终调用的代码在io.netty.channel.nio.AbstractNioChannel#doBeginRead()
里面,其中有句selectionKey.interestOps(interestOps | readInterestOp),就
是通过这个interestOps来完成注册SelectionKey#OP_ACCEPT的。

以前翻看代码时没在意readInterestOp这个变量,完全按字面意思去理解它,以
为它最多只是注册SelectionKey#OP_READ,多次忽略了这里的逻辑。后来翻看
io.netty.channel.socket.nio.NioServerSocketChannel.NioServerSocketChannel
的构造方法可以看到它传了SelectionKey.OP_ACCEPT进去的(见下面的代码),
传进去后被赋值到readInterestOp变量里面。这个变量如果叫做acceptOrReadInterestOp
就更好了,我可以少走一些弯路。。。
public NioServerSocketChannel(ServerSocketChannel channel) {
super(null, channel, SelectionKey.OP_ACCEPT);
config = new NioServerSocketChannelConfig(this, javaChannel().socket());
}

好了,知道在哪里注册SelectionKey.OP_ACCEPT之后,又是由哪里触发这个注册呢?
我debug追踪io.netty.example.echo.EchoServer这个经典的例子来看了一把,得到的流程:
-> io.netty.bootstrap.ServerBootstrap#bind(xxx)
-> io.netty.bootstrap.AbstractBootstrap#doBind0(xxx)
-> io.netty.channel.AbstractChannel#bind(xxx)
-> io.netty.channel.DefaultChannelPipeline#bind(xxx)
-> io.netty.channel.DefaultChannelPipeline#invokeBind(xxx)
-> io.netty.channel.DefaultChannelPipeline.HeadHandler#bind(xxx)
-> io.netty.channel.AbstractChannel.AbstractUnsafe#bind(xxx)
在上面这个AbstractUnsafe#bind里面有段关键代码(见下面的代码),之前也是一直被我忽略,最终需要执行里面的pipeline.fireChannelActive():
if (!wasActive && isActive()) {
invokeLater(new OneTimeTask() {
@Override
public void run() {
pipeline.fireChannelActive();
}
});
}

通过继续追踪fireChannelActive()就可以看到io.netty.channel.nio.AbstractNioChannel#doBeginRead()的执行了,然后就是selectionKey.interestOps(interestOps | readInterestOp)来完成注册SelectionKey#OP_ACCEPT。

发布在 http://auzll.iteye.com
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值