I have a difficult time understanding how to use Chunks with Netty 4.
What I'm trying to do is to somehow replace a servlet keeping the connection opened and sending data twice per second.
So, I've looked at the headers returned by the servlet and now have a Netty handler extending ChannelInboundMessageHandlerAdapter<FullHttpRequest>.
I'm actually doing something like this in my messageReceived(...) method:
HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
HttpResponseStatus.OK);
// initialize response
HttpHeaders headers = response.headers();
headers.set(HttpHeaders.Names.CONTENT_TYPE, "text/event-stream");
headers.set(HttpHeaders.Names.CACHE_CONTROL,
"no-cache, no-store, max-age=0, must-revalidate");
headers.set(HttpHeaders.Names.PRAGMA, HttpHeaders.Values.NO_CACHE);
headers.set(HttpHeaders.Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED);
ctx.write(response);
I've added a ChunkedWriteHandler in my pipeline just before the above handler code.
Now, if I got this right, I'm now supposed to write ChunkedInputs in my channel in order to send pieces of data.
I've create a ChunkedInput subclass like this one:
private class MyChunk implements ChunkedByteInput {
private final ChannelHandlerContext ctx;
private final String json;
private boolean done = false;
private HystrixChunk2(ChannelHandlerContext ctx, String json) {
this.ctx = ctx;
this.json = json;
}
@Override
public boolean readChunk(ByteBuf buffer) throws Exception {
buffer.writeBytes("data: ".getBytes())
.writeBytes(json.getBytes())
.writeBytes("\n".getBytes());
done = true;
LOGGER.info("Wrote chunck");
return true;
}
@Override
public boolean isEndOfInput() throws Exception {
return done;
}
@Override
public void close() throws Exception {
ctx.channel().close();
}
}
And basically in my messageReceived(..) method, I simply write some instance of that class.
But I may either have found a bug, or more likely don't understand how to use chunks with Netty, because nothing gets written on the output of my socket...