2

Netty 4.1.2.Final

Here is my pipeline:

pipeline.addLast(new HttpServerCodec());
pipeline.addLast(new HttpObjectAggregator(65536));
pipeline.addLast(new ChunkedWriteHandler());
pipeline.addLast(new HttpInboundHandler());

Here is HttpInboundHandler class:

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();
  }

}

Here is the HTTP request

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

Here is the HTTP response

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

0

The "HelloWorld" does not appear in the response, but only a zero -length chunked is received. What is the problem?

Mr.Wang from Next Door
  • 13,670
  • 12
  • 64
  • 97

1 Answers1

1

Reason found, DefaultFullHttpResponse can not be used with ChunkedWriteHandler. Should use DefaultHttpResponse instead.

Mr.Wang from Next Door
  • 13,670
  • 12
  • 64
  • 97