【问题标题】:netty how to make server program not to quitnetty如何使服务器程序不退出
【发布时间】:2014-12-14 19:06:12
【问题描述】:

我试图在我的项目中理解和使用 Netty,所以从 Netty 用户指南中的基本 DiscardServer 示例开始。

下面几乎是原始代码的复制粘贴...

public void run() throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap sb = new ServerBootstrap();
        sb.group(bossGroup, workerGroup);
        sb.channel(NioServerSocketChannel.class);
        sb.childHandler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new DiscardServerHandler());
            }
        });

        // Set some socket options such as socket queue backlog and keepalive.
        sb.option(ChannelOption.SO_BACKLOG, 128);
        sb.childOption(ChannelOption.SO_KEEPALIVE, true);

        // bind to port and start listening.
        ChannelFuture f = sb.bind(port).sync();

    } finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }
}

当我创建一个 main 方法时,如下所示,它运行良好,但随后就被终止了。

public static void main(String[] args) throws Exception {

    int port = Integer.parseInt(args[0]);
    System.out.println("Starting discard server...");
    new DiscardServer(port).run();
    System.out.println("Discard server returning...");
}

程序输出为:

开始丢弃服务器... 丢弃服务器返回...

然后程序终止。

我期望 netty 类中的事件循环应该成为我的服务器,但它似乎并没有那样发生。我应该在我的 main 方法中编写一个 while 循环来确保我的服务器继续运行吗?

更新:

如果我使用 Netty 4.x 系列的 jar 文件,同样的程序可以完美运行。我认为第 5 版仍在不断发展,因此预计会出现错误。

【问题讨论】:

    标签: netty


    【解决方案1】:

    您忘记添加等待关闭操作:

    // Bind and start to accept incoming connections.
    ChannelFuture f = b.bind(PORT).sync();
    // Wait until the server socket is closed.
    // In this example, this does not happen, but you can do that to gracefully
    // shut down your server.
    f.channel().closeFuture().sync();
    

    您现在要做的是启动服务器进行侦听,然后在关闭执行程序后完成您自己的主程序。

    您必须阻止某些事情,而对于服务器而言,最好的方法是等待 closeFuture 操作。

    然后在您的处理程序中,您必须决定何时关闭服务器(f.channel().close()),这将转为唤醒主程序并完成服务器。

    重要提示:您必须区分“子”通道(您从处理程序中的ctx.channel() 获得,附加到一个唯一的客户端连接)和“父”通道(您从ctx.channel().parent() 获得)。关闭“子”不会终止f.channel(),因为这是“父”(监听器)。所以你必须做类似ctx.channel().parent().close()的事情。

    请注意,DiscardServerHandler 的当前示例不包含任何要停止的代码(它是一个永远运行的处理程序)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多