netty NioServerSocketChannel注册流程一

  netty server端启动一般用以下代码:

	ServerBootstrap bootstrap = new ServerBootstrap();
		NioEventLoopGroup boss = new NioEventLoopGroup(1);
		NioEventLoopGroup work = new NioEventLoopGroup(2 * Runtime.getRuntime().availableProcessors());
		bootstrap.group(boss, work);
		bootstrap.channel(NioServerSocketChannel.class);
		bootstrap.localAddress("localhost", 8081);
		bootstrap.childHandler(new ChannelInitializer<Channel>() {
			@Override
			protected void initChannel(Channel ch) throws Exception {
				ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, Delimiters.lineDelimiter()));
				ch.pipeline().addLast(new StringDecoder(StandardCharsets.UTF_8));
				ch.pipeline().addLast(new EchoHandlerTest());
			}
		});

		try {
			// 开始绑定server,阻塞直到绑定成功
			ChannelFuture channelFuture = bootstrap.bind().sync();
			
			System.out.println(">server started");
			
			//阻塞直到关闭成功
			channelFuture.channel().closeFuture().sync();
			
			System.out.println(">server close");
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			// 关闭资源,boss线程组及work线程组
			boss.shutdownGracefully();
			work.shutdownGracefully();
		}


    而核心流程是 bootstrap.bind() 绑定流程。简单来讲,主要是:

    1.创建NioServerSocketChannel

    2.向操作系统申请socket文件句柄

    3.初始化NioServerSocketChannel的pipeLine及相应属性

    4.分配个boss线程,并启动它,由它来完成以下事情

    5.将该channel注册到selector上。底层看是epoll还是其它reactor技术实现。做的事情就是将该channel对应socket文件句柄关心的事件注册到操作系统。这里为0,先不注册感兴趣事件。

   6.调用socket bind方法,让操作系统开启一条tcp连接。

   7.如果autoRead属性为true(默认为true)则马上将accept事件注册到selector上。

   执行完这些步骤后,boss线程就不断轮循,看是否有感兴趣事件发生,这里为连接事件。

   流程图如下:

  


  

    

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值