nettydirect-buffer

How do I correctly work with ByteToMessageCodec.encode and direct buffers


I use a ByteToMessageCodec in my netty project. The encode has the following structure:

protected abstract void encode(
    ChannelHandlerContext ctx,
    I msg,
    ByteBuf out
) throws Exception

In my case the msg is a message that holds a directBuffer that came from another channel and is to be forwarded.

My Questions:

There is a source by norman maurer telling something about this exact topic, but it seems to memory copy the buffers and doesn't answer all my questions.


Solution

  • You should not use a ByteToMessageCodec at all and just use MessageToMessageEncoder in this case:

    Then you could do:

    protected abstract void encode(ChannelHandlerContext ctx, I msg, List<Object> out) {
        out.add(msg.directBuffer);
    }
    

    This will prevent any memory copies.