2015-06-20 35 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