Netty网络编程-服务端启动
1、Netty的Handler模型
2、服务端代码示例
根据模型图可以更好的理解ServerBootstrap引导类设置Netty的属性。
public class TimeServer {
private int port;
public TimeServer(int port) {
this.port = port;
}
public void run() throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup,workGroup)
//设置使用的使用的Channel类
.channel(NioServerSocketChannel.class)
//设置NioServerSocketChannel的Pipeline的Handler
.handler(null)
// 用于设置ServerChannel的选项,如:NioServerSocketChanne,来监听和接收connection。作用于当bind() 时。
.option(ChannelOption.SO_BACKLOG, 128)
//设置NioServerSocketChannel 附带的属性
//.attr()
//用于设置SocketChannel,作用于connection成功后channel的I/O操作。
.childOption(ChannelOption.SO_KEEPALIVE, true)
//设置SocketChannel 附带的属性
//.childAttr()
//设置连接SocketChannel的的handler
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline().addLast(new TimeServerHandler());
}
});
ChannelFuture f = b.bind(port).sync();
f.addListener((ChannelFutureListener) future -> System.out.println("服务启动完毕"));
f.channel().closeFuture().sync();
} finally {
workGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
}