Home > Software design >  Netty doesn't complain if port is already used
Netty doesn't complain if port is already used

Time:05-24

Following problem: I expect an exception if a port is already used.

So I tried to start my server twice in a thread

    public void start() {
    new Thread(new Runnable() {
        @Override
        public void run() {
            EventLoopGroup bossGroup = new EpollEventLoopGroup();
            EventLoopGroup workerGroup = new EpollEventLoopGroup();

            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(final SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast("decoder", new Decoder(Server.this));
                            socketChannel.pipeline().addLast("encoder", new Encoder(Server.this));
                        }
                    });

            serverBootstrap.bind(port).channel().closeFuture().syncUninterruptibly();
        }
    }).start();
}

But got no exception. I also tried to add an channel handler and catch a exception there, no luck :/

Surrounding the line with bind(port) to catch an exception has also no effect. But I noticed when I added a ChannelListener to the ChannelFuture, that one of the started instances never reached that point.

Anyone an idea?

CodePudding user response:

After binding you are directly taking the channel from the future, but it probably hasn’t finished at that point. Try to wait for your bind to complete with bind(port).sync().

See for reference https://www.baeldung.com/netty#6-server-bootstrap and https://netty.io/4.1/api/io/netty/channel/ChannelFuture.html

  • Related