Netty中封装了对Http chunked协议的支持,使用方式如下:
1 write一个response,且设置chunked参数,告知客户端将返回chunked类型数据;
2 开始写chunk数据;
3 按照chunk协议标准返回chunk数据结束标记;
4 关闭channel连接。
具体代码如下:
HttpRequest req = (HttpRequest) reqObj;
HttpResponse resp = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
HttpResponseStatus.OK);
resp.setChunked(true);
resp.setHeader(HttpHeaders.Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED);
ChannelFuture f = ctx.getChannel().write(resp);
String str = "my test chunked data!";
HttpChunk chunk = new DefaultHttpChunk(ChannelBuffers.wrappedBuffer(str.toString().getBytes(CharsetUtil.UTF_8)));
f = ctx.getChannel().write(chunk);
HttpChunk chunk = new DefaultHttpChunk(ChannelBuffers.EMPTY_BUFFER);
f = ctx.getChannel().write(chunk);
f.addListener(ChannelFutureListener.CLOSE);
ps:chunked的数据大小可根据实际情况自己定义。