在没有closeFuture()的情况下在Netty中运行多个服务器.sync()

koe*_*e10 3 java netty

我正在研究Netty应用程序.我想在不同的端口上运行多个服务器,没有(阻塞)就无法运行closeFuture().sync().

ServerManager使用以下代码在我的类中启动服务器:

gpcmServer = new GpcmServer(port);

gpspServer = new GpspServer(port);
Run Code Online (Sandbox Code Playgroud)

在这些类中,我按如下方式启动服务器:

public GpspServer(int port) throws InterruptedException {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            // Add the server handler and its decoder
                            ch.pipeline().addLast(new GpspDecoder(), new GpspServerHandler());
                        }
                    })
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true);

            // Bind and start to accept incoming connections.
            bindFuture = bootstrap.bind(port).sync();

            bindFuture.channel().closeFuture();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }
Run Code Online (Sandbox Code Playgroud)

但是,当我不打电话时,我无法连接到服务器closeFuture().sync().当我添加.sync()bindFuture.channel().closeFuture(),我可以连接到服务器.我如何继续这样做,仍然使服务器工作?

tru*_*tin 7

当您调用EventLoopGroup.shutdown*()方法时,事件循环将关闭它正在管理的所有套接字和服务器套接字,然后再终止自身.因此,如果您没有等到服务器套接字关闭,则您的finally块将完全终止您的服务器.

您实际需要做的是运行多个服务器:

  • 绑定多次,
  • 在您想要关闭服务器之前不要打电话shutdownGracefully().