title: Netty 4 : Write ByteBuf as a HTTP Chunk
body: <p>Netty 4.1.2.Final</p>
  
  <p>Here is my pipeline:</p>
  
  <pre><code>pipeline.addLast(new HttpServerCodec());
  pipeline.addLast(new HttpObjectAggregator(65536));
  pipeline.addLast(new ChunkedWriteHandler());
  pipeline.addLast(new HttpInboundHandler());
  </code></pre>
  
  <p>Here is <code>HttpInboundHandler</code> class:</p>
  
  <pre><code>class HttpInboundHandler extends SimpleChannelInboundHandler&lt;FullHttpRequest&gt; {
  
    @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();
    }
  
  }
  </code></pre>
  
  <p>Here is the HTTP request</p>
  
  <pre><code>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
  </code></pre>
  
  <p>Here is the HTTP response</p>
  
  <pre><code>HTTP/1.1 200 OK
  transfer-encoding: chunked
  connection: keep-alive
  
  0
  </code></pre>
  
  <p>The "<code>HelloWorld</code>" does not appear in the response, but only a zero -length chunked is received.  What is the problem?</p>