Simon2215
Simon2215

Reputation: 232

Netty doesn't complain if port is already used

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?

Upvotes: 1

Views: 359

Answers (1)

slindenau
slindenau

Reputation: 1267

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

Upvotes: 2

Related Questions