【超详细解释】从Java NIO到Netty的每一步 (八)

本文深入探讨Netty的bind启动源码,从初始化和注册逻辑到端口绑定,揭示Netty如何将ServerSocketChannel注册到selector并绑定端口,以及在pipeline中传播ChannelActive事件。通过分析,读者可以更好地理解Netty与Java NIO的关系及工作原理。
摘要由CSDN通过智能技术生成

Netty 源码解读

bind启动源码

我们的服务是通过下面代码进行绑定端口并启动的,所以我们从bind()方法开始分析

ChannelFuture f = b.bind(port).sync();

一直跟进到io.netty.bootstrap.AbstractBootstrap#doBind方法

private ChannelFuture doBind(final SocketAddress localAddress) {
   
        //1 初始化和注册逻辑
        final ChannelFuture regFuture = initAndRegister();
        final Channel channel = regFuture.channel();
        if (regFuture.cause() != null) {
   
            return regFuture;
        }

        if (regFuture.isDone()) 
            ChannelPromise promise = channel.newPromise();
            //2 端口绑定逻辑
            doBind0(regFuture, channel, localAddress, promise);
            return promise;
        } else {
   
            final PendingRegistrationPromise promise = new PendingRegistrationPromise(channel);
            regFuture.addListener(new ChannelFutureListener() {
   
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
   
                    Throwable cause = future.cause();
                    if (cause != null) {
   
                         promise.setFailure(cause);
                    } else {
   
                        promise.registered();

                        doBind0(regFuture, channel, localAddress, promise);
                    }
                }
            });
            return promise;
        }
    }

1.初始化和注册逻辑

继续跟进initAndRegister()方法,根绝下面的注释,你类比一下Java NIO的代码,你会不会有莫名的亲切感?

final ChannelFuture initAndRegister() {
   
        Channel channel = null;
        try {
   
            //(1)创建ServerSocketChannel
            channel = channelFactory.newChannel();
            //初始化Channel,不展开说明了
            init(channel);
        } catch (Throwable t) {
   
            if (channel != null) 
                channel.unsafe().closeForcibly();
            }
            return new DefaultChannelPromise(channel, GlobalEventExecutor.INSTANCE).setFailure(t);
        }
        //(2)注册selector
        ChannelFuture regFuture = config().group().register(channel)
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

牛战士从不脱下面具

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值