在netty SimpleChannelInboundHandler中正确使用AUTO_READ

时间:2018-07-07 07:31:36

标签: netty

我正在将代码从netty 3.8版本迁移到netty 4.1 我使用带有netty的http服务器,下面是HTTP服务器的代码

public class SimpleHTTPServer {

      public void start() {
          try {
              ServerBootstrap b = new ServerBootstrap();
              EventLoopGroup bossGroup = new NioEventLoopGroup();
              EventLoopGroup workerGroup = new NioEventLoopGroup();

              b.group(bossGroup, workerGroup)

                      .channel(NioServerSocketChannel.class)
                      .childHandler(new ChannelInitializer<SocketChannel>() {
                          @Override
                          public void initChannel(SocketChannel ch) {
                              ch.pipeline().addLast("codec", new HttpServerCodec());
                              ch.pipeline().addLast("aggregator",
                                      new HttpObjectAggregator(512 * 1024));
                              ch.pipeline().addLast("request",
                                      new SimpleHTTPHandler());
                          }
                      })
                      .option(ChannelOption.SO_BACKLOG, 128)
                      .childOption(ChannelOption.WRITE_BUFFER_WATER_MARK, WriteBufferWaterMark.DEFAULT)
                      .childOption(ChannelOption.AUTO_READ, false)
                      .childOption(ChannelOption.SO_KEEPALIVE, true);

              ChannelFuture f = b.bind(5055).sync();
              f.channel().closeFuture().sync();

          } catch (Exception e) {
              e.printStackTrace();
          }
      }
  }

下面是频道处理程序代码

public class SimpleHTTPHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

        protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) {
            HttpResponseStatus responseStatus = OK;
            FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, responseStatus, Unpooled.copiedBuffer("My Netty".getBytes()));
            response.headers().add(request.headers());
            response.headers().set(CONTENT_LENGTH, response.content().readableBytes());
            if (isKeepAlive(request)) {
                response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);
            }
            ctx.writeAndFlush(response);
        }

        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            super.channelActive(ctx);
            ctx.channel().read();
        }
    }

我在here中将HTTPServer中的AUTO_READ选项设置为false,然后在此不提及在channelHandler中处理通道消息。 Netty ChannelRead method is not getting invoked

因此,我手动调用了读取的通道。 这段代码中ChannelOption.AUTO_READ是否正确处理?

1 个答案:

答案 0 :(得分:1)

在您收到ctx.read()中的请求后,我想您仍然无法再致电channelRead0(...)。如果您不打电话,您将不会再收到任何请求,这很可能不是您想要的。

您还很可能希望将ctx.channel().read()替换为ctx.read(),以便开始让出站事件由当前处理程序处理,并且不要使其流过整个管道(如果有的话)在触发读取的处理程序之后,还有更多处理程序。