Netty: listening on multiple addresses / ports with one ServerBootstrap

I currently don't know how to listen to netty on multiple addresses / ports. I want to create a small HTTP server that serves a dedicated application. I need to run it on multiple 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();
    }
}

      

Thank!

+3


source to share


1 answer


Just call a bind(...)

few 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();
}

      

+5


source







All Articles