码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2020-04-04 22:24:40      阅读:102      评论:0      收藏:0      [点我收藏+]

标签:channel   auth   ted   netty   ios   rri   sel   node   cto   

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()

NioServerSocketChannelConfig()

AbstractionNioChannel()

  configureBlocking(false)

  

2、初始化channel

3、注册selector

4、绑定端口

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

标签:channel   auth   ted   netty   ios   rri   sel   node   cto   

原文地址:https://www.cnblogs.com/xiaofeiyang/p/12634545.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!