Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the main thread back in Netty ServerSocket

I had a question about how I could get the master thread back in Netty while creating a TCP server socket.

In the code below taken from here, "Hello Hello" would never be written in the output as the thread that starts the Server, waits on this line: f.channel().closeFuture().sync();. Do I need to create a separate thread to get the main thread back in this case or is there any way in Netty that would allow me to do so (getting the main thread back while having the TCP running in the background)?

public void start() throws Exception {
    NioEventLoopGroup group = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(group)
         .channel(NioServerSocketChannel.class)
         .localAddress(new InetSocketAddress(port))
         .childHandler(new ChannelInitializer<SocketChannel>() {
             @Override
             public void initChannel(SocketChannel ch) 
                 throws Exception {
                 ch.pipeline().addLast(
                         new EchoServerHandler());
             }
         });

        ChannelFuture f = b.bind().sync();
        System.out.println(EchoServer.class.getName() + " started and listen on " + f.channel().localAddress());
        f.channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully().sync();
    }
}

public static void main(String[] args) throws Exception {
    if (args.length != 1) {
        System.err.println(
                "Usage: " + EchoServer.class.getSimpleName() +
                " <port>");
        return;
    }
    int port = Integer.parseInt(args[0]);
    new EchoServer(port).start();
    System.out.println("Hello Hello");
}
like image 452
Hossein Avatar asked Oct 18 '22 13:10

Hossein


1 Answers

You are not required to wait for the closefuture. This is only done in the tutorials to make the the event loop group is properly closed.

You can remove the f.channel().closeFuture().sync(); and the group.shutdownGracefully().sync(); line from your program to make it non-blocking.

Make sure to call f.channel().close(), then f.channel().closeFuture().sync() and finally group.shutdownGracefully().sync(); when shutting down your main program to make sure the Netty stack is properly stopped

like image 113
Ferrybig Avatar answered Oct 31 '22 12:10

Ferrybig