美文网首页
Netty server 主动关闭

Netty server 主动关闭

作者: lesliefang | 来源:发表于2024-03-24 22:45 被阅读0次
    package com.braun.pumpd.netty;
    
    import io.netty.bootstrap.ServerBootstrap;
    import io.netty.channel.*;
    import io.netty.channel.nio.NioEventLoopGroup;
    import io.netty.channel.socket.SocketChannel;
    import io.netty.channel.socket.nio.NioServerSocketChannel;
    
    public class NettyServer {
        public static final int PORT = 5000;
        private Channel serverChannel;
    
        public void start() throws Exception {
            EventLoopGroup bossGroup = new NioEventLoopGroup();
            EventLoopGroup workerGroup = new NioEventLoopGroup();
            try {
                ServerBootstrap b = new ServerBootstrap();
                b.group(bossGroup, workerGroup)
                        .channel(NioServerSocketChannel.class)
                        .option(ChannelOption.SO_BACKLOG, 100)
                        .childHandler(new ChannelInitializer<SocketChannel>() {
                            @Override
                            public void initChannel(SocketChannel ch) throws Exception {
    
                            }
                        });
    
                ChannelFuture f = b.bind(PORT).sync();
                // 保存 serverChannel, 之后调用  close, closeFuture sync 的阻塞就会解除了
                serverChannel = f.channel();
                System.out.println("server started at port " + PORT);
                // 这里 sync 会一直阻塞
                f.channel().closeFuture().sync();
    
            } finally {
                bossGroup.shutdownGracefully();
                workerGroup.shutdownGracefully();
            }
    
            System.out.println("server closed");
        }
    
        public void stop() {
            if (serverChannel != null) {
                serverChannel.close();
                serverChannel = null;
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:Netty server 主动关闭

          本文链接:https://www.haomeiwen.com/subject/uwyrtjtx.html