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

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

最佳答案

只需多次调用 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();
}

关于java - Netty:使用单个 ServerBootstrap 监听多个地址/端口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30957207/

相关文章:

java - 使用签名不匹配解密 hyperlocal (Google RTB)

java - messageReceived (netty) 未调用

Netty 4 - 直接将ByteBuf写入 channel ,绕过管道

ssl - Netty 设置 SSL 握手超时不起作用

ssl - 宁异步http客户端如何接受任何证书

java - java中 'EST'时区的两个日期之间的差异

Java Kafka 消费者和 avro 反序列化器

java - 如果我要求用户输入一个文件,而该文件不存在,如何在程序不停止的情况下继续询问文件名?

java - Netty SslHandler 抛出 IllegalReferenceCountException

java - glBufferSubData 导致缓冲区用零填充