一个简单的netty socket服务端。
我是在web项目里面启动netty的
如何在web容器关闭的时候 关闭netty呢。
就是说关闭方法怎么写呢。
public static void start(int port) throws InterruptedException { try { sb.option(ChannelOption.SO_BACKLOG, 1024); sb.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8)); // p.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8)); p.addLast(new NettyServerHandler()); } }); Channel ch = sb.bind(port).sync().channel(); log.info("server 127.0.0.1:" + port + " is starting"); ch.closeFuture().addListener(new WebSocketListener()).sync(); }finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
在定义一个ServletContextListener,
在contextDestroyed中调用
{
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}