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

use*_*396 3 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

Nor*_*rer 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();
}
Run Code Online (Sandbox Code Playgroud)