2015-06-20 594 views
2

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

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

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

谢谢!

回答

4

多次拨打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(); 
} 
+1

感谢您的回答!我使用Netty 5.0.0.Alpha2,那里,boostrap.bind(..)返回一个ChannelFuture,所以我不能再次调用bind(..)。因此,如果我在一个循环中执行此操作,应如何使用channel.closeFuture()。sync();关闭所有创建的通道,而此功能是否为阻塞通道? – user3641396

+0

@ user3641396据我所知,循环只是为了防止程序退出。它在列表中的第一个未来将开始阻塞,但如果关闭ServerBootstrap,则通道将开始关闭。循环确保它们全部关闭。 – sja