Netty 4:将ByteBuf写为HTTP Chunk

时间:2016-07-16 04:06:04

标签: netty

Netty 4.1.2.Final

这是我的管道:

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请求

GET / HTTP/1.1
Host: 127.0.0.1:8888
Connection: keep-alive
Cache-Control: max-age=0
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en,zh-CN;q=0.8,zh;q=0.6

这是HTTP响应

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

0

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

1 个答案:

答案 0 :(得分:1)

找到原因,DefaultFullHttpResponse无法与ChunkedWriteHandler一起使用。应该使用DefaultHttpResponse代替。