本文介绍了Netty java从ByteBuf获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在下面的代码中有效地从 ByteBuf
获取字节数组?我需要获取数组然后序列化它。
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();
}
}
推荐答案
ByteBuf buf = ...
byte[] bytes = new byte[buf.readableBytes()];
buf.readBytes(bytes);
如果您不想更改readerIndex:
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);
如果要最小化内存副本,可以使用<$ c $的后备数组c> ByteBuf ,如果可用:
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;
}
请注意,你不能简单地使用 buf .array()
,因为:
Please note that you can't simply use buf.array()
, because:
- 并非所有
ByteBuf
有后备阵列。一些是堆外缓冲区(即直接内存) - 即使
ByteBuf
有一个支持数组(即 buf.hasArray()返回true
),以下不一定是真的,因为缓冲区可能是其他缓冲区的一个片段或池化缓冲区:
-
buf.array()[0] == buf.getByte(0)
-
buf.array()。length == buf.capacity()
- Not all
ByteBuf
s have backing array. Some are off-heap buffers (i.e. direct memory) - Even if a
ByteBuf
has a backing array (i.e.buf.hasArray()
returnstrue
), 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()
这篇关于Netty java从ByteBuf获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
-