Unpooled工具类

ByteBuf缓冲区
在netty缓冲区buffer中不需要使用flip进行反转
netty缓冲区分成三段:
0——readerIndex 已读区
readerIndex——writerIndex 可读区
writerIndex——Capacity 可写区
getByte(i)读数据,readerIndex不会变
public static void main(String[] args) {
//1,创建一个byte[10]数组
//2,在netty缓冲区buffer中不需要使用flip进行反转
ByteBuf buf = Unpooled.buffer(10);
for (int i = 0; i < 10; i++) {
buf.writeByte(i);
}
System.out.println("capacity:" + buf.capacity());//10
//输出
for (int i = 0; i < buf.capacity(); i++) {
System.out.println(buf.getByte(i));
}
}
通过调试可看到
写时:writerIndex是一直在增加
读时:取readerIndex到writerIndex之间的值,所以不用flip反转

readByte()读数据,readerIndex会变
for (int i = 0; i < buf.capacity(); i++) {
System.out.println(buf.readByte());
}


本文介绍Netty中的缓冲区管理方式,重点讲解Unpooled工具类的使用及ByteBuf缓冲区的特点。Netty缓冲区分为三个区域:已读区、可读区和可写区,文章通过实例演示了如何利用ByteBuf进行数据读写操作,强调了Netty缓冲区无需使用flip反转的优势。

1000

被折叠的 条评论
为什么被折叠?



