Netty源码解析(2):服务端启动

package com.xiaofeiyang;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.AttributeKey;

/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-04-02 12:23
 */
public final class NioServer {

    public static void main(String[] args) throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childOption(ChannelOption.TCP_NODELAY, true)
                    .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();
        }
    }
}

 

1、创建服务端channel

  bind()

    initAndRegister()

      channelFactory.newChannel()

其中channelFactory通过反射创建channel。channelFactory通过NioServerSocketChannel创建一个channelFactory。

NioServerSocketChannel 通过构造方法时通过

newSocket() 通过jdk来创建底层jdk  channel

NioServerSocketChannelConfig() tcp参数配置类

AbstractionNioChannel() 

  configureBlocking(false) 设置阻塞模式

  AbstractChannel()创建 id unsafe pipeline,unsafe所有对tcp底层操作,pipeline业务操作管道

2、初始化channel

init() 初始化入口

  set ChannelOptions,ChannelAttrs

  set ChildOptions,ChildAttrs

  config handler 配置服务端pipeline

  add ServerBootstrapAcceptor 添加连接器

3、注册selector

channel初始化完成后就要注册到selector上去

AbstractChannel.register(channel)入口

  this.eventLoop = eventLoop绑定线程

  resgister0() 实际注册

    doRegister() 调用底层jdk注册

    invokeHandlerAddedIfNeeded()

    fireChannelRegistered()传播事件  

4、绑定端口

AbstractUnsafe.bind() 入口

  doBind()

    javaChannel().bind() jdk底层绑定

  pipeline.fireChannelActive() 传播事件

    HeadContext.channelActive() 绑定连接接入事件

      ChannelHandlerContext.fireChannelActive()

      readIfIsAutoRead();

    TailContext.

posted on 2020-04-04 21:59  清浊  阅读(150)  评论(0编辑  收藏  举报