Netty五不听java

时间:2015-09-26 09:41:15

标签: java netty

我的netty 5服务器有问题,它只是在我启动后立即关机,这应该不会发生,它应该是在监听端口并继续运行 我使用netty 5 alpha 2所以这里是我的代码:

网络管理器:

public class NetworkManager {

    private ChannelHandler handler;
    private ChannelInitializer initializer;
    private ServerBootstrap bootstrap;
    private SocketAddress address;

    // Executors
    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;

    public NetworkManager(int port) {
        handler = new ChannelHandler();
        initializer = new ChannelInitializer(handler);
        bootstrap = new ServerBootstrap();
        address = new InetSocketAddress(port);
        bossGroup = new NioEventLoopGroup();
        workerGroup = new NioEventLoopGroup();
    }

    public void init() {
        bootstrap.group(bossGroup, workerGroup)
        .channel(NioServerSocketChannel.class)
        .option(ChannelOption.SO_REUSEADDR, true)
        .childOption(ChannelOption.SO_KEEPALIVE, true)
        .childOption(ChannelOption.TCP_NODELAY, true)
        .childOption(ChannelOption.SO_BACKLOG, 128)
        .childHandler(initializer);
    }

    public void bind() {
        try {
            bootstrap.bind(address).sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void destroy() {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }
}

`

Server.java: `

public static void main(String[] args) {
    init();
    start();
}

private static NetworkManager network;

public static void init() {
    Settings.init();
    network = new NetworkManager(Settings.networkPort);
    network.init();
}

public static void start() {
    network.bind();

}

任何其他必需的信息,请告诉我生病编辑帖子

1 个答案:

答案 0 :(得分:2)

这是一个重复的问题。 See here

简而言之:

您忘了在关闭操作中添加等待:

// 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操作。