//服务类
ServerBootstrap bootstrap = new ServerBootstrap();
//Boss Work
NioEventLoopGroup boss = new NioEventLoopGroup();
NioEventLoopGroup work = new NioEventLoopGroup();
try {
//设置线程
bootstrap.group(boss, work);
//设置socket工厂
bootstrap.channel(NioServerSocketChannel.class);
//设置pipe工厂
bootstrap.childHandler(new ChannelInitializer<Channel>() {
protected void initChannel(Channel ch) throws Exception {
ch.pipeline().addLast(new StringDecoder());
ch.pipeline().addLast(new StringEncoder());
ch.pipeline().addLast(new ServerHandler());
};
});
//设置参数
bootstrap.option(ChannelOption.SO_BACKLOG, 2048);//serverSocketChannel的设置 连接缓冲池 最大等待连接数 2048
//SocketChannel设置
bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);//自动关闭连接 维持链接活跃 清除死链接
bootstrap.childOption(ChannelOption.TCP_NODELAY, true);
ChannelFuture future = bootstrap.bind(new InetSocketAddress(7000));
System.out.println("start");
//等待channel关闭
future.channel().closeFuture().sync();
System.out.println("sync");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
System.out.println("finally");
//释放资源
boss.shutdownGracefully();
work.shutdownGracefully();
}
}
本文地址:https://www.stanwind.com/post/15
版权声明:若无注明,本文皆为“Make it Better”原创,转载请保留文章出处。