WaliedYassen
WaliedYassen

Reputation: 65

Netty five not listening java

i have problem with my netty 5 server, it just shutdown right after i launch which should not happen, it should be listening to a port and keep running i use netty 5 alpha 2 so here's my code:

NetworkManager:

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();

}

Any other required informations, please tell me ill edit the post

Upvotes: 0

Views: 179

Answers (1)

Frederic Brégier
Frederic Brégier

Reputation: 2206

This is a duplicate question. See here

In short:

You forgot to add the wait on close operation:

// 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();

What you do right now is starting the server to listen, then finishing your own main after shutdown your executors.

You have to block on something, and the best for the server is to wait on the closeFuture operation.

Upvotes: 2

Related Questions