在https://blog.csdn.net/ybin__/article/details/81007018 中分析了NioEventGroupLoop的初始化,这一章主要ServerBootstrap的初始化,及Netty服务端的启动。
- ServerBootstrap的UML图:
ServerBootstrap继承至AbstractBootstrap,ServerBootStrap初始化的时候会将服务端的NioEventGroupLoop,handler及配置保存至AbstractBootStrap中,将客户端的配置保存至ServerBootStrap中。
服务端初始化代码:
public void run() {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workGroup = new NioEventLoopGroup();
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workGroup) //1.保存NioEventLoopGroup
.channel(NioServerSocketChannel.class) //2.设置服务端channel
.option(ChannelOption.SO_BACKLOG, 128) //3.保存服务端配置
.childOption(ChannelOption.SO_KEEPALIVE, true) //4.保存客户端配置
.handler(new ChannelHandler()) //5.保存服务端handler
.childHandler(new ChannelInitializer<SocketChannel>() { //6.保存客户端handler
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline().addLast(new ChannelInboundA(), new ChannelInboundB(), new ChannelInboundC());
}
});