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();
}
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线程就不断轮循,看是否有感兴趣事件发生,这里为连接事件。
流程图如下: