框架Netty TCP服务监听多个端口

Java 01-07 14:27

启动一个同时监听 8000 和 8001 端口的服务。


void startTcpServer() {

  def port1 = 8000
  def port2 = 8001

  ServerBootstrap b = new ServerBootstrap()
  EventLoopGroup bossGroup = new NioEventLoopGroup()
  EventLoopGroup workerGroup = new NioEventLoopGroup()

  b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
    .option(ChannelOption.SO_REUSEADDR, true)
    .childHandler(new ChannelInitializer() {
    protected void initChannel(Channel ch) throws Exception {
      ch.pipeline()
     .addLast("logging", new LoggingHandler(LogLevel.INFO))
     .addLast(new SimpleChannelInboundHandler() {
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
           String strMsg = msg.toString(CharsetUtil.UTF_8);
           println "recv: $strMsg"
        }
     })
    }
  })

  b.bind(port1).sync()
  println "tcp server($port1) is started.."

  b.bind(port2).sync()
  println "tcp server($port2) is started.."

}

重点代码:.option(ChannelOption.SO_REUSEADDR, true)

总结:使用 netty 监听多个端口分两步完成:

1、设置 ServerBootStrap 参数 .option(ChannelOption.SO_REUSEADDR, true),重用同一地址

2、通过 ServerBootStrap 绑定多个监听端口

 

相关推荐