Jire
Jire

Reputation: 10290

Netty: How can I reuse the same `FullHttpResponse`?

In my project I'd like to write the same FullHttpResponse to many clients for a performance boost.

Previously I have written the same ByteBuf for a custom protocol, and used retain to prevent the buf from being released after writing.

Unfortunately with FullHttpResponse (DefaultFullHttpResponse) my technique doesn't seem to work. The first time I write the response clients receive the response correctly, but the next write doesn't go through.

I did a simple System.out.println test to make sure nothing was blocking and that my code was executed entirely, and my test showed that yes, nothing is blocking and the request does seem to go through.

I am using the Netty 4.1.0.Final release from Maven Central.


The pipeline only has an HttpServerCodec(256, 512, 512, false, 64) and my SimpleChannelInboundHandler<HttpRequest>, which I send the FullHttpResponse from.

Here's a simplified version of my inbound handler:

class HTTPHandler extends SimpleChannelInboundHandler<HttpRequest> {

    private static final FullHttpResponse response =
            new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, 
                                        HttpResponseStatus.OK,
                                        Unpooled.buffer(8).writeLong(0),
                                        false);

    @Override
    public void channelRead0(ChannelHandlerContext ctx, HttpRequest msg) {
        ctx.writeAndFlush(response.retain(), ctx.voidPromise());
    }

}

Upvotes: 1

Views: 558

Answers (1)

Norman Maurer
Norman Maurer

Reputation: 23567

You need to use response.duplicate().retain() or if using Netty 4.1.x you can also use response.retainedDuplicate().

This is needed to ensure you get separate reader/writer indices.

Upvotes: 3

Related Questions