netty-3

代码:

public final class Server {

    public static void main(String[] args) throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);// 对应的开线程去accept
        EventLoopGroup workerGroup = new NioEventLoopGroup();// 服务端处理客户端的数据

        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup) // 配置进去
                    .channel(NioServerSocketChannel.class) // 设置服务端的socketChannel就是socket
                    .childOption(ChannelOption.TCP_NODELAY, true) // 给客户端的连接设置基本的tcp属性
                    .childAttr(AttributeKey.newInstance("childAttr"), "childAttrValue") // 每次创建客户端连接绑定基本的属性
                    .handler(new ServerHandler()) // 打印状态信息
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) {// 数据流读写的处理逻辑
                            ch.pipeline().addLast(new AuthHandler());
                            //..
                        }
                    });

            ChannelFuture f = b.bind(8888).sync();
            f.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}

------------------------------------------3-1-------------------------------------------

服务端启动的四个过程:

1.创建服务端channel

2.初始化服务端channel

3.注册selector

4.端口绑定

---------------------------------------------------------------------------------

1.创建服务端channel:

第一步:入口

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

第二步:一直跟进去

第三步:

 final ChannelFuture initAndRegister() {
        Channel channel = null;
        try {
            channel = channelFactory.newChannel();
            init(channel);
        } catch (Throwable t) {
            if (channel != null) {
                channel.unsafe().closeForcibly();
            }
            return new DefaultChannelPromise(channel, GlobalEventExecutor.INSTANCE).setFailure(t);
        }

        ChannelFuture regFuture = config().group().register(channel);
        if (regFuture.cause() != null) {
            if (channel.isRegistered()) {
                channel.close();
            } else {
                channel.unsafe().closeForcibly();
            }
        }

        return regFuture;
    }

第四步:进去newChannel

   @Override
    public T newChannel() {
        try {
            return clazz.newInstance();// 通过反射new的channel
        } catch (Throwable t) {
            throw new ChannelException("Unable to create Channel from class " + clazz, t);
        }
    }

第五步:我们看下clazz是什么就是一个channel,首先看下channelFactory是在哪里初始化的。

我们看下这个.channel到底做了哪些事情

   public B channel(Class<? extends C> channelClass) {
        if (channelClass == null) {
            throw new NullPointerException("channelClass");
        }
        return channelFactory(new ReflectiveChannelFactory<C>(channelClass));
    }

第六步:我们只需要关注,通过NioServerSocketChannel这个了构造了一个反射的工厂。

new ReflectiveChannelFactory<C>(channelClass)

所以综合就是传入这个类,通过反射的方式调用这个类的构造函数。

过程:

概括为:

第一个过程:在NioServerSocketChannel的构造函数中我们创建了一个jdk原生的ServerSocketChannel

 public NioServerSocketChannel() {
        this(newSocket(DEFAULT_SELECTOR_PROVIDER));
    }
  private static ServerSocketChannel newSocket(SelectorProvider provider) {
        try {
            /**
             *  Use the {@link SelectorProvider} to open {@link SocketChannel} and so remove condition in
             *  {@link SelectorProvider#provider()} which is called by each ServerSocketChannel.open() otherwise.
             *
             *  See <a href="https://github.com/netty/netty/issues/2308">#2308</a>.
             */
            return provider.openServerSocketChannel();
        } catch (IOException e) {
            throw new ChannelException(
                    "Failed to open a server socket.", e);
        }
    }

第二个过程:tcp参数 ,通过NioServerSocketChannelConfig配置服务端Channel的构造函数

 public NioServerSocketChannel(ServerSocketChannel channel) {
        super(null, channel, SelectionKey.OP_ACCEPT);
        config = new NioServerSocketChannelConfig(this, javaChannel().socket());
    }

第三个过程,调用父类的构造函数

进去:NIO编程,主要是配置NIO的SocketChannel是非阻塞的

  protected AbstractNioChannel(Channel parent, SelectableChannel ch, int readInterestOp) {
        super(parent);
        this.ch = ch;
        this.readInterestOp = readInterestOp;
        try {
            ch.configureBlocking(false);// 配置 Java NIO SocketChannel 为非阻塞的
        } catch (IOException e) {
            try {
                ch.close();
            } catch (IOException e2) {
                if (logger.isWarnEnabled()) {
                    logger.warn(
                            "Failed to close a partially initialized socket.", e2);
                }
            }

            throw new ChannelException("Failed to enter non-blocking mode.", e);
        }
    }

第四个过程:第、调用AbstractChannel这个抽象类的构造函数设置Channel的id(每个Channel都有一个id,唯一标识),unsafe(tcp相关底层操作),pipeline(逻辑链)等,而不管是服务的Channel还是客户端的Channel都继承自这个抽象类,他们也都会有上述相应的属性。我们看下AbstractChannel的构造函数

不管是服务端还是客户端的Channel都集成自这个抽象的Channel,其中传入了id unsafe这个是tcp读写操作的一个类  逻辑链。

 protected AbstractChannel(Channel parent) {
        this.parent = parent;
        id = newId();//创建Channel唯一标识 
        unsafe = newUnsafe();//netty封装的TCP 相关操作类
        pipeline = newChannelPipeline();//逻辑链
    }

总结:服务端的channel是反射创建的。

------------------------------------------3-2-------------------------------------------

第一步:配置用户自定义的ChannelOptions和ChannelAttrs,这个用的不是很对

第二步:配置用户自定义的ChildOptions和ChildAttrs,这个每次创建新的来连接都会自定义这两个属性。

第三步:配置服务端的pipeLine。通过header设置进去的。

第四步:给accept的新连接分配一个nio的线程。

总结:

设置ChannelOptions、ChannelAttrs ,配置服务端Channel的相关属性;
设置ChildOptions、ChildAttrs,配置每个新连接的Channel的相关属性;
Config handler,配置服务端pipeline;
add ServerBootstrapAcceptor,添加连接器,对accpet接受到的新连接进行处理,添加一个nio线程;

第一步:

第二步:我们分析的代码

 @Override
        }

        final Map<ChannelOption<?>, Object> options = options0();
        synchronized (options) {
            channel.config().setOptions(options);// 设置NioServerSocketChannel相应的TCP参数,其实这一步就是把options设置到channel的config中
        }

        final Map<AttributeKey<?>, Object> attrs = attrs0();// 绑定用户自定义的属性
        synchronized (attrs) {
            for (Entry<AttributeKey<?>, Object> e: attrs.entrySet()) {
                @SuppressWarnings("unchecked")
                AttributeKey<Object> key = (AttributeKey<Object>) e.getKey();
                channel.attr(key).set(e.getValue());
            }
        }

        ChannelPipeline p = channel.pipeline();

        final EventLoopGroup currentChildGroup = childGroup;
        final ChannelHandler currentChildHandler = childHandler;
        final Entry<ChannelOption<?>, Object>[] currentChildOptions;
        final Entry<AttributeKey<?>, Object>[] currentChildAttrs;
        synchronized (childOptions) {// 1
            currentChildOptions = childOptions.entrySet().toArray(newOptionArray(childOptions.size()));
        }
        synchronized (childAttrs) {// 2
            currentChildAttrs = childAttrs.entrySet().toArray(newAttrArray(childAttrs.size()));
        }

        p.addLast(new ChannelInitializer<Channel>() {// 对服务端Channel的handler进行配置
            @Override
            public void initChannel(Channel ch) throws Exception {
                final ChannelPipeline pipeline = ch.pipeline();
                ChannelHandler handler = config.handler(); // 自定义的handler添加进去
                if (handler != null) {
                    pipeline.addLast(handler);
                }

                ch.eventLoop().execute(new Runnable() {
                    @Override
                    public void run() {
                        pipeline.addLast(new ServerBootstrapAcceptor(
                                currentChildGroup, currentChildHandler, currentChildOptions, currentChildAttrs));
                    }
                });
            }
        });
    }

第三步:

服务端启动会默认添加特殊的处理器。

 ch.eventLoop().execute(new Runnable() {
                    @Override
                    public void run() {//在这里会把我们自定义的ChildGroup、ChildHandler、ChildOptions、ChildAttrs相关配置传入到ServerBootstrapAcceptor构造函数中,并绑定到新的连接上
                        pipeline.addLast(new ServerBootstrapAcceptor(
                                currentChildGroup, currentChildHandler, currentChildOptions, currentChildAttrs));
                    }
                });

currentChildHandler:我们自己定义的。

总结:保存属性,创建连接接入器,每次accept新的连接都会对连接进行配置。

------------------------------------------3-3-------------------------------------------

一个服务端的Channel创建完毕后,下一步就是要把它注册到一个事件轮询器Selector上,在initAndRegister()中我们把上面初始化的Channel进行注册。

找到这个:

 final ChannelFuture initAndRegister() {
        Channel channel = null;
        try {
            channel = channelFactory.newChannel();
            init(channel);
        } catch (Throwable t) {
            if (channel != null) {
                channel.unsafe().closeForcibly();
            }
            return new DefaultChannelPromise(channel, GlobalEventExecutor.INSTANCE).setFailure(t);
        }

        ChannelFuture regFuture = config().group().register(channel);// 这个方法
        if (regFuture.cause() != null) {
            if (channel.isRegistered()) {
                channel.close();
            } else {
                channel.unsafe().closeForcibly();
            }
        }
        return regFuture;
    }
    @Override
        public final void register(EventLoop eventLoop, final ChannelPromise promise) {
            if (eventLoop == null) {
                throw new NullPointerException("eventLoop");
            }
            if (isRegistered()) {
                promise.setFailure(new IllegalStateException("registered to an event loop already"));
                return;
            }
            if (!isCompatible(eventLoop)) {
                promise.setFailure(
                        new IllegalStateException("incompatible event loop type: " + eventLoop.getClass().getName()));
                return;
            }

            AbstractChannel.this.eventLoop = eventLoop;

            if (eventLoop.inEventLoop()) {
                register0(promise);
            } else {
                try {
                    eventLoop.execute(new Runnable() {
                        @Override
                        public void run() {
                            register0(promise);
                        }
                    });
                } catch (Throwable t) {
                    logger.warn(
                            "Force-closing a channel whose registration task was not accepted by an event loop: {}",
                            AbstractChannel.this, t);
                    closeForcibly();
                    closeFuture.setClosed();
                    safeSetFailure(promise, t);
                }
            }
        }

逻辑概括:

点进去register0我们主要的关注点在doRegister方法。

  @Override
    protected void doRegister() throws Exception {
        boolean selected = false;
        for (;;) {
            try {
                selectionKey = javaChannel().register(eventLoop().selector, 0, this);
                return;
            } catch (CancelledKeyException e) {
                if (!selected) {
                    eventLoop().selectNow();
                    selected = true;
                } else {
                    throw e;
                }
            }
        }
    }

进去register0,进入doRegister,this就是服务端得的channel,我们绑定到selector上面去。

回到用户代码:

进入这里可以看到事件的回调:

 @Override
    public void channelActive(ChannelHandlerContext ctx) {
        System.out.println("channelActive");
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) {
        System.out.println("channelRegistered");
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) {
        System.out.println("handlerAdded");
    }

根据流程主要触发后两个事件。

-------------------------------------------3-4-----------------------------------------

端口的绑定:

我们进入doBind方法进行分析:

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

        if (regFuture.isDone()) {
            ChannelPromise promise = channel.newPromise();
            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;
        }
    }

我们看下doBind0。

我们进入到AbstrateChannel看下:

       @Override
        public final void bind(final SocketAddress localAddress, final ChannelPromise promise) {
            assertEventLoop();

            if (!promise.setUncancellable() || !ensureOpen(promise)) {
                return;
            }
            if (Boolean.TRUE.equals(config().getOption(ChannelOption.SO_BROADCAST)) &&
                localAddress instanceof InetSocketAddress &&
                !((InetSocketAddress) localAddress).getAddress().isAnyLocalAddress() &&
                !PlatformDependent.isWindows() && !PlatformDependent.isRoot()) {
                logger.warn(
                        "A non-root user can't receive a broadcast packet if the socket " +
                        "is not bound to a wildcard address; binding to a non-wildcard " +
                        "address (" + localAddress + ") anyway as requested.");
            }

            boolean wasActive = isActive();判断绑定是否完成
            try {
                doBind(localAddress);//底层jdk绑定端口
            } catch (Throwable t) {
                safeSetFailure(promise, t);
                closeIfClosed();
                return;
            }

            if (!wasActive && isActive()) {
                invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        pipeline.fireChannelActive();
                    }
                });
            }

            safeSetSuccess(promise);
        }

进入doBind方法:

 @Override
    protected void doBind(SocketAddress localAddress) throws Exception {
        if (PlatformDependent.javaVersion() >= 7) {
            javaChannel().bind(localAddress, config.getBacklog());// JDk底层的channel
        } else {
            javaChannel().socket().bind(localAddress, config.getBacklog());
        }
    }

进入:在 pipeline.fireChannelActive()中会触发pipeline中的channelActive()方法

调用readIfIsAutoRead函数一直跟:

上面那些参数是怎么来的?

总结:调用jdk的api作为实际的绑定,触发事件,调用redisIfIsAutoRead,层层调用到doBeginRead方法。

在doBeginRead()方法,netty会把accept事件注册到Selector上。

-------------------------------------------3-5-----------------------------------------

总结:

总结:调用newChannel()创建服务端的channel,过程实际上就是调用JDK底层的API,创建一个JDK的内存,netty将其包装为一个,自己的服务端的channel,同时会创建一些基本的组件,比如pipline,同时调用init方法,初始化服务端的channel,为服务端channel添加一个连接处理器。随后调用register方法,注册selector,绑定到JDK底层的channel,调用JDK底层的api实现。

-------------------------------------------------------------3-6-------------------------------------------------------------

最后的总结看下这篇文章:https://www.cnblogs.com/dafanjoy/p/9810189.html

发布了374 篇原创文章 · 获赞 12 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_28764557/article/details/104834193