Netty 4:将ByteBuf作为HTTP块写入

Netty 4:将ByteBuf作为HTTP块写入,netty,Netty,Netty 4.1.2.最终版本 这是我的管道: pipeline.addLast(new HttpServerCodec()); pipeline.addLast(new HttpObjectAggregator(65536)); pipeline.addLast(new ChunkedWriteHandler()); pipeline.addLast(new HttpInboundHandler()); 以下是HttpInboundHandler类: class HttpInboundHa

Netty 4.1.2.最终版本

这是我的管道:

pipeline.addLast(new HttpServerCodec());
pipeline.addLast(new HttpObjectAggregator(65536));
pipeline.addLast(new ChunkedWriteHandler());
pipeline.addLast(new HttpInboundHandler());
以下是
HttpInboundHandler
类:

class HttpInboundHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

  @Override
  protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg)
      throws Exception {

    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    response.headers().set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
    if (HttpUtil.isKeepAlive(msg)) {
      response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
    }

    // Write the initial line and the header.
    ctx.write(response);

    if (msg.method() == HttpMethod.GET) {
      ByteBuf buf = Unpooled.copiedBuffer("HelloWorld", CharsetUtil.UTF_8);
      ByteBufInputStream contentStream = new ByteBufInputStream(buf);

      // Write the content and flush it.
      ctx.writeAndFlush(new HttpChunkedInput(new ChunkedStream(contentStream)));

      //ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
      //

    }

  }

  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
    cause.printStackTrace();
    ctx.close();
  }

}
下面是HTTP响应

HTTP/1.1 200 OK
transfer-encoding: chunked
connection: keep-alive

0

响应中没有出现“
HelloWorld
”,但只接收到长度为零的分块。问题是什么?

原因是,
DefaultFullHttpResponse
不能与
ChunkedWriteHandler
一起使用。应改用
DefaultHttpResponse

HTTP/1.1 200 OK
transfer-encoding: chunked
connection: keep-alive

0