如何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();
}
}
Run Code Online (Sandbox Code Playgroud)
tru*_*tin 66
ByteBuf buf = ...
byte[] bytes = new byte[buf.readableBytes()];
buf.readBytes(bytes);
Run Code Online (Sandbox Code Playgroud)
如果您不希望readerIndex更改:
ByteBuf buf = ...
byte[] bytes = new byte[buf.readableBytes()];
int readerIndex = buf.readerIndex();
buf.getBytes(readerIndex, bytes);
Run Code Online (Sandbox Code Playgroud)
如果要最小化内存副本,可以使用它的后备数组(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;
}
Run Code Online (Sandbox Code Playgroud)
请注意,您不能简单地使用buf.array()
,因为:
ByteBuf
都有支持阵列.一些是堆外缓冲区(即直接内存)ByteBuf
具有后备数组(即buf.hasArray()
返回true
),以下情况也不一定正确,因为缓冲区可能是其他缓冲区或池缓冲区的片段:
buf.array()[0] == buf.getByte(0)
buf.array().length == buf.capacity()
另一种选择是ByteBufUtil.getBytes(ByteBuf buf, int start, int length, boolean copy)
归档时间: |
|
查看次数: |
29517 次 |
最近记录: |