Netty java 从 ByteBuf 获取数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19296386/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 15:47:14  来源:igfitidea点击:

Netty java getting data from ByteBuf

javanetty

提问by NiceTheo

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

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

}

采纳答案by trustin

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

If you don't want the readerIndex to change:

如果您不希望 readerIndex 改变:

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如果可用):

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:

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

  • Not all ByteBufs have backing array. Some are off-heap buffers (i.e. direct memory)
  • Even if a ByteBufhas 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()
  • 并非所有ByteBufs 都有后备数组。有些是堆外缓冲区(即直接内存)
  • 即使 aByteBuf有一个后备数组(即buf.hasArray()返回true),以下情况也不一定正确,因为缓冲区可能是其他缓冲区的一部分或池缓冲区:
    • buf.array()[0] == buf.getByte(0)
    • buf.array().length == buf.capacity()