Netty:使用单个ServerBootstrap监听多个地址/端口

时间:2015-06-20 17:59:06

标签: java netty

我目前不知道如何在多个地址/端口上监听netty。我想构建一个服务于特殊应用程序的小型HTTP服务器。我需要在几个地址(如IPv4和IPv6)和端口(443/80)上运行它。

对于每个听众,我想使用相同的处理程序。我目前的代码如下:

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

1 个答案:

答案 0 :(得分:5)

只需多次致电bind(...)

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