Netty:使用单个 ServerBootstrap 监听多个地址/端口
Netty: Listen on several addresses / ports with a single ServerBootstrap
我目前不知道如何在多个地址/端口上使用 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();
}
我目前不知道如何在多个地址/端口上使用 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();
}