内置通信传输模式
java
try {
//父子EventLoop
serverBootstrap.group(boss,work)
//指定使用NIO的通信模式
.channel(NioServerSocketChannel.class)
.localAddress(new InetSocketAddress(port))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
//为每个Channel添加一个共享的Handler
socketChannel.pipeline().addLast(msgCountHandler);
socketChannel.pipeline().addLast(new EchoServceHandler());
}
});
//异步绑定到服务器,sync()会阻塞到完成
ChannelFuture sync = serverBootstrap.bind().sync();
//阻塞当前线程,直到服务器的ServerChannel被关闭
sync.channel().closeFuture().sync();
} finally {
boss.shutdownGracefully().sync();
work.shutdownGracefully().sync();
}
NioServerSocketChannel
NIO 内部是基于 Selector 实现的。
EpollServerSocketChannel
由 JNI 驱动的 epoll()和非阻塞 IO,完全非阻塞。
Only supported on Linux,只支持Linux
Epoll使用方法
- 将 NioEventLoopGroup 替换为 EpollEventLoopGroup 。
- 将 NioServerSocketChannel.class 替换为 EpollServerSocketChannel.class 即可。