服务器端代码
public class TimeServer {
public void bind(int port) throws Exception{
//创建两NioEventLoopGroup实例。
//NioEventLoopGroup是个线程组。
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try{
//创建ServerBootstrap对象,它是Netty用于启动NIO服务端的辅助启动类,目的是降低服务端的开发复杂度。
ServerBootstrap b = new ServerBootstrap();
//调用ServerBootstrap的group方法,将两个NIO线程组当做入参传递到ServerBootstrap中。
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 1024)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline().addLast(new TimeServerHandler());
}
});
ChannelFuture f = b.bind(port).sync();
//等待服务锻炼路关闭之后main函数才退出。
f.channel().closeFuture().sync();
}finally {
//优雅退出,释放线程池资源。
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception{
int port = 8088;
new TimeServer().bind(port);
}
}
Netty服务器端Handler端代码