Reputation: 53
I currently have no idea how to listen with netty on multiple addresses / ports. I want to build a little HTTP Server which serves an special application. I need to run it on several addresses (like IPv4 and IPv6) and ports (443 / 80).
For each listener I want to use the same handlers. My current code looks like this:
public void run() {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.option(ChannelOption.SO_BACKLOG, 1024);
bootstrap.group(bossGroup, workerGroup)
.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
.channel(NioServerSocketChannel.class)
.childHandler(new ApplicationServerInitializer());
Channel channel = bootstrap.bind(this.socketAddress).sync().channel();
logger.info("Started HTTP Server on {}:{}", this.socketAddress.getHostName(), this.socketAddress.getPort());
channel.closeFuture().sync();
} catch(Throwable throwable) {
logger.error("An error occurred while starting the HTTP- Server", throwable);
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
Upvotes: 3
Views: 5266
Reputation: 23567
Just call bind(...)
multiple times.
List<ChannelFuture> futures = new ArrayList<>();
futures.add(bootstrap.bind(this.socketAddress(IPV4, 80)));
futures.add(bootstrap.bind(this.socketAddress(IPV4, 443)));
futures.add(bootstrap.bind(this.socketAddress(IPV6, 80)));
futures.add(bootstrap.bind(this.socketAddress(IPV6, 443)));
for (ChannelFuture f: futures) {
f.sync();
}
Upvotes: 5