I'm working on a Netty application. I want to run multiple servers on different ports and that is not working without the (blocking) closeFuture().sync().
I start the servers in my ServerManager class using the following code:
gpcmServer = new GpcmServer(port);
gpspServer = new GpspServer(port);
In those classes, I start the server as follows:
public GpspServer(int port) throws InterruptedException {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
// Add the server handler and its decoder
ch.pipeline().addLast(new GpspDecoder(), new GpspServerHandler());
}
})
.option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true);
// Bind and start to accept incoming connections.
bindFuture = bootstrap.bind(port).sync();
bindFuture.channel().closeFuture();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
However, I can't connect to the server when I don't call closeFuture().sync(). When I add .sync() to bindFuture.channel().closeFuture(), I can connect to the server. How can I keep doing it this way and still make the server work?
When you call EventLoopGroup.shutdown*() method, the event loop will close all sockets and server sockets it is managing before terminating itself. Therefore, if you did not wait until the server socket is closed, your finally block will terminate your server completely.
What you actually need to do to run multiple servers is:
shutdownGracefully() until you want to shut your server down.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With