netty核心源码 二 服务端和客户端启动流程

  • Post author:
  • Post category:其他


通过前面的一篇,我们知道了channelpipeline的执行顺序和基本方法,再开始学习DefaultChannelPipeline实现之前,我们先来分析两个类

ServerBootstrap和Bootstrap   他们有一个共同的父类AbstractBootstrap



服务端流程




客户端流程


先看看其成员变量

private volatile EventLoopGroup group;//这个接口的核心是next()
    private volatile SocketAddress localAddress;//网路地址
    private final Map<ChannelOption<?>, Object> options = new LinkedHashMap<ChannelOption<?>, Object>();//channel配置
    private final Map<AttributeKey<?>, Object> attrs = new LinkedHashMap<AttributeKey<?>, Object>();//基础配置
    private volatile ChannelHandler handler;//业务处理类

其核心方法bind()

    /**
     * Create a new {@link Channel} and bind it.
     */
    public ChannelFuture bind(SocketAddress localAddress) {
        validate();
        if (localAddress == null) {
            throw new NullPointerException("localAddress");
        }
        return doBind(localAddress);
    }

    private ChannelFuture doBind(final SocketAddress localAddress) {
        final ChannelFuture regFuture = initAndRegister();
        final Channel channel = regFuture.channel();
        if (regFuture.cause() != null) {
            return regFuture;
        }

        final ChannelPromise promise;
        if (regFuture.isDone()) {
            promise = channel.newPromise();
            doBind0(regFuture, channel, localAddress, promise);
        } else {
            // Registration future is almost always fulfilled already, but just in case it's not.
            promise = new DefaultChannelPromise(channel, GlobalEventExecutor.INSTANCE);
            regFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    doBind0(regFuture, channel, localAddress, promise);
                }
            });
        }

        return promise;
    }



版权声明:本文为akfly原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。