netty如何使服务器程序不要退出

时间:2014-12-14 08:29:37

标签: netty

我试图在我的项目中理解和使用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仍在不断发展,因此预计会出现错误。

1 个答案:

答案 0 :(得分: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()),这将转向唤醒主程序并完成服务器。

重要提示:您必须区分&#34;孩子&#34; channel(从你的处理程序中的ctx.channel()获得,附加到一个唯一的客户端连接)和&#34; parent&#34;频道(来自ctx.channel().parent())。关闭孩子&#34;不会终止f.channel(),因为这是父母&#34;一个(听众)。所以你必须做ctx.channel().parent().close()

之类的事情

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

相关问题