nettynetty4

Difference between writing a ByteBuf and an ordinary Java Objects


I noticed it is possible to eother write data which is an instance of ByteBuff or plain Java Objects when using Netty.

As can be seen in the HAProxyClient

On that file you have

HAProxyMessage message = new HAProxyMessage(
                    HAProxyProtocolVersion.V2, 
                    HAProxyCommand.PROXY, HAProxyProxiedProtocol.TCP4,
                    "127.0.0.1", 
                    "127.0.0.2", 
                    8000, 
                    9000
);

ch.writeAndFlush(message).sync();

Where a normal Java object, HAProxyMessage was written to the context. Still on the same file, you have:

ch.writeAndFlush(Unpooled.copiedBuffer("Hello World!", CharsetUtil.US_ASCII)).sync();

Where Unpooled.copiedBuffer is used to create the data to be written. This method returns a ByteBuf.

The question then is: what is the material difference (if any) between writing (or reading) a plan Java object and a ByteBuf


Solution

  • When you write a ByteBuf, the message does not need any conversion. When it is a Java Object, you need an encoder/decoder. Here you have the following:

    They transform the Java Object to ByteBuf (Encoder) or reversely (Decoder).

    The way you want to use one or the other depends on you current case:

    But finally, in Netty, everything is a ByteBuf.