1 Star 0 Fork 0

方温南/学习文档

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
ByteBuf 1.78 KB
一键复制 编辑 原始数据 按行查看 历史
方温南 提交于 2020-06-22 09:33 +08:00 . 2020.06.22-整合公司电脑学习笔记
ByteBuf
提供了读索引和写索引来控制字节数组
1.维护了readerIndex和writerIndex
2.readerIndex大于writerIndex时会抛出越界异常
3.ByteBuf容量=writerIndex
4.ByteBuf可读容量=writerIndex-readerIndex
5.readXXX()和writeXXX()方法将会推进其对应的索引
6.getXXX()和setXXX()方法将对两个索引无影响
使用模式分为:
1.HeapBuffer
2.DirectBuffer
3.CompositeBuffer
HeapBuffer:
public static void heapBuffer() {
// 创建Java堆缓冲区
ByteBuf heapBuf = Unpooled.buffer();
if (heapBuf.hasArray()) { // 是数组支撑
byte[] array = heapBuf.array();
int offset = heapBuf.arrayOffset() + heapBuf.readerIndex();
int length = heapBuf.readableBytes();
handleArray(array, offset, length);
}
}
DirectBuffer:
public static void directBuffer() {
ByteBuf directBuf = Unpooled.directBuffer();
if (!directBuf.hasArray()) {
int length = directBuf.readableBytes();
byte[] array = new byte[length];
directBuf.getBytes(directBuf.readerIndex(), array);
handleArray(array, 0, length);
}
}
CompositeBuffer:
本质上类似于提供一个或多个ByteBuf的组合视图,可以根据需要添加和删除不同类型的ByteBuf
public static void byteBufComposite() {
// 复合缓冲区,只是提供一个视图
CompositeByteBuf messageBuf = Unpooled.compositeBuffer();
ByteBuf headerBuf = Unpooled.buffer(); // can be backing or direct
ByteBuf bodyBuf = Unpooled.directBuffer(); // can be backing or direct
messageBuf.addComponents(headerBuf, bodyBuf);
messageBuf.removeComponent(0); // remove the header
for (ByteBuf buf : messageBuf) {
System.out.println(buf.toString());
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Java
1
https://gitee.com/nanwenfang/learning_documents.git
git@gitee.com:nanwenfang/learning_documents.git
nanwenfang
learning_documents
学习文档
master

搜索帮助