Netty 4:将 ByteBuf 写为 HTTP 块 [英] Netty 4 : Write ByteBuf as a HTTP Chunk

查看:95
本文介绍了Netty 4:将 ByteBuf 写为 HTTP 块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Netty 4.1.2.Final

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

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

这是 HTTP 响应

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

0

HelloWorld"没有出现在响应中,但只收到一个零长度的分块.有什么问题?

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

推荐答案

原因找到,DefaultFullHttpResponse 不能与 ChunkedWriteHandler 一起使用.应该使用 DefaultHttpResponse 代替.

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

这篇关于Netty 4:将 ByteBuf 写为 HTTP 块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆