30

How to get a byte array from ByteBuf efficiently in the code below? I need to get the array and then serialize it.

package testingNetty;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class ServerHandler extends  ChannelInboundHandlerAdapter {
     @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) {
         System.out.println("Message receive");
         ByteBuf buff = (ByteBuf) msg;
             // There is I need get bytes from buff and make serialization
         byte[] bytes = BuffConvertor.GetBytes(buff);
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { 
            // Close the connection when an exception is raised.
            cause.printStackTrace();
            ctx.close();
        }

}
Artemkller545
  • 979
  • 3
  • 21
  • 55
NiceTheo
  • 752
  • 1
  • 7
  • 16

2 Answers2

89
ByteBuf buf = ...
byte[] bytes = new byte[buf.readableBytes()];
buf.readBytes(bytes);

If you don't want the readerIndex to change:

ByteBuf buf = ...
byte[] bytes = new byte[buf.readableBytes()];
int readerIndex = buf.readerIndex();
buf.getBytes(readerIndex, bytes);

If you want to minimize the memory copy, you can use the backing array of the ByteBuf, if it's available:

ByteBuf buf = ...
byte[] bytes;
int offset;
int length = buf.readableBytes();

if (buf.hasArray()) {
    bytes = buf.array();
    offset = buf.arrayOffset();
} else {
    bytes = new byte[length];
    buf.getBytes(buf.readerIndex(), bytes);
    offset = 0;
}

Please note that you can't simply use buf.array(), because:

  • Not all ByteBufs have backing array. Some are off-heap buffers (i.e. direct memory)
  • Even if a ByteBuf has a backing array (i.e. buf.hasArray() returns true), the following isn't necessarily true because the buffer might be a slice of other buffer or a pooled buffer:
    • buf.array()[0] == buf.getByte(0)
    • buf.array().length == buf.capacity()
trustin
  • 12,231
  • 6
  • 42
  • 52
  • 2
    [@user2132106 would like to know](http://stackoverflow.com/a/28122795/2778484) if he can do `byte[] ar= buf.array()` (if I understand the post correctly). – chappjc Feb 19 '15 at 22:03
  • Updated the answer for him. – trustin Feb 21 '15 at 03:06
  • @trustin what's the purpose of the `offset` here? – Fireburn Nov 10 '20 at 20:06
  • I tested with real data: the second way (minimize the memory copy) is wrong. Java platform: Oracle 1.8; netty version: 4.1.58.Final. – zipper Mar 02 '21 at 10:37
  • @Fireburn `offset` tells at which position in the array the first byte starts. – trustin Mar 03 '21 at 12:22
  • @trustin -- tested the second method and I occasionally got wrong byte array contents. May be need careful consideration and add some protection? – zipper Mar 05 '21 at 13:15
  • @zipper May be you are not using offset while reading data from byte array. – Udit Sep 04 '21 at 21:06
  • What happens to `bytes` in third approach if it was initialized in first block i.e. `bytes = buf.array()` and later buf was released - `buf.release()` ? – ygogia Aug 09 '22 at 04:59
4

Another option is ByteBufUtil.getBytes(ByteBuf buf, int start, int length, boolean copy)

See ByteBufUtil

Lion
  • 965
  • 10
  • 21