2016-07-16 66 views
2

的Netty 4.1.2.Final的Netty 4:寫ByteBuf作爲HTTP組塊

這裏是我的管道:

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」沒有出現在響應,但只有一個零-length分塊被接收。問題是什麼?

回答

0

找到原因,DefaultFullHttpResponse不能與ChunkedWriteHandler一起使用。應該用DefaultHttpResponse代替。