Unpooled类
Netty 提供一个专门用来操作缓冲区(即Netty的数据容器)的工具类
常用方法如下所示
public static ByteBuf copiedBuffer(CharSequence string, Charset charset)
通过给定的数据和字符编码返回一个 ByteBuf
对象(类似于 NIO 中的 ByteBuffer 但有区别)
public static ByteBuf buffer(int initialCapacity)
获取指定容量的ByteBuf对象
ByteBuf
ByteBuf是一个byte存放的缓冲区。
ByteBuf通过两个位置的指针来协助缓冲区的读写操作,读操作使用readIndex
,写操作使用writeIndex
。

discardable bytes 丢弃的读空间
readable bytes 可读空间
writeable bytes 可写空间

- 创建对象,该对象包含一个数组arr , 是一个byte[10]
- 在netty 的buffer中,不需要使用flip 进行反转 。底层维护了 readerIndex 和 writerIndex
- 通过 readerIndex 和 writerIndex 和 capacity, 将buffer分成三个区域
- 0—readerIndex 已经读取的区域
- readerIndex—writerIndex , 可读的区域
- riterIndex – capacity, 可写的区域

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| public class NettyByteBuf01 { public static void main(String[] args) {
ByteBuf buffer = Unpooled.buffer(10);
for(int i = 0; i < 10; i++) { buffer.writeByte(i); }
System.out.println("capacity=" + buffer.capacity());
for(int i = 0; i < buffer.capacity(); i++) { System.out.println(buffer.readByte()); } System.out.println("执行完毕"); } }
|

hasArray()
判断是否存在数组
array()
获取数组对象
arrayOffset()
数组偏移量
readerIndex()
获取readerIndex值
writerIndex()
获取writerIndex值
capacity()
获取当前容量
getByte()
获取指定位置字节
readableBytes()
当前可读字节数
getCharSequence()
按照某个范围获取字符序列

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| public class NettyByteBuf02 { public static void main(String[] args) {
ByteBuf byteBuf = Unpooled.copiedBuffer("hello,world!", Charset.forName("utf-8"));
if(byteBuf.hasArray()) {
byte[] content = byteBuf.array();
System.out.println(new String(content, Charset.forName("utf-8")));
System.out.println("byteBuf=" + byteBuf);
System.out.println(byteBuf.arrayOffset()); System.out.println(byteBuf.readerIndex()); System.out.println(byteBuf.writerIndex()); System.out.println(byteBuf.capacity());
System.out.println(byteBuf.getByte(0));
int len = byteBuf.readableBytes(); System.out.println("len=" + len);
for(int i = 0; i < len; i++) { System.out.println((char) byteBuf.getByte(i)); }
System.out.println(byteBuf.getCharSequence(0, 4, Charset.forName("utf-8"))); System.out.println(byteBuf.getCharSequence(4, 6, Charset.forName("utf-8")));
}
} }
|