Netty java 从 ByteBuf 获取数据

2022-09-01 11:14:49

如何在下面的代码中有效地获得字节数组?我需要获取数组,然后对其进行序列化。ByteBuf

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();
        }

}

答案 1
ByteBuf buf = ...
byte[] bytes = new byte[buf.readableBytes()];
buf.readBytes(bytes);

如果您不希望读取器索引更改:

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

如果要最小化内存副本,可以使用 的支持数组(如果可用):ByteBuf

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;
}

请注意,您不能简单地使用 ,因为:buf.array()

  • 并非所有 s 都有后备阵列。有些是堆外缓冲区(即直接内存)ByteBuf
  • 即使 a 具有支持数组(即 returns ),则不一定为真,因为缓冲区可能是其他缓冲区的切片或合并缓冲区:ByteBufbuf.hasArray()true
    • buf.array()[0] == buf.getByte(0)
    • buf.array().length == buf.capacity()

答案 2

推荐