package com.hao.netty.buf;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
/**
* @author haoxiansheng
* @date 2020-05-24
*/
public class NettyByteBuf01 {
public static void main(String[] args) {
/**
* 创建一个ByteBuf
* 1、创建 对象 该对象包含一个数组arr,是一个byte[10]
* 2、在netty 的buffer中不需要使用flip进行读写切换
* 因为底层 维护了readerIndex 和 writerIndex
* 3、通过readerIndex 和 writerIndex capacity将buffer分成了三个区域
* 0 --- readerIndex 已经读取的区域
* readerIndex ---- writerIndex 可读的区域
* writerIndex ----- capacity 可写入的区域
*/
ByteBuf byteBuf = Unpooled.buffer(10);
for (int i = 0; i < 10; i++) {
byteBuf.writeByte(i);
}
System.out.println("capacity" + byteBuf.capacity());
// 输出
for (int i = 0; i < byteBuf.capacity(); i++) {
//System.out.println(byteBuf.getByte(i));
System.out.println(byteBuf.readByte()); // 这个readerIndex 会逐渐变大
}
}
}
package com.hao.netty.buf;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.util.CharsetUtil;
import java.nio.charset.Charset;
/**
* @author haoxiansheng
* @date 2020-05-24
*/
public class NettyByteBuf02 {
public static void main(String[] args) {
// 创建 ByteBuf
ByteBuf byteBuf = Unpooled.copiedBuffer("hello ,world", Charset.forName("utf-8"));
// 使用相关的方法
if (byteBuf.hasArray()) { // true
byte[] content = byteBuf.array();
// 将content 转成字符串
System.out.println(new String(content, Charset.forName("utf-8")));
System.out.println(byteBuf.readerIndex()); // 0
System.out.println(byteBuf.arrayOffset()); // 0
System.out.println(byteBuf.readerIndex()); // 12
System.out.println(byteBuf.capacity()); // 36
int len = byteBuf.readableBytes(); // 返回可读区的字节数 12
System.out.println(len);
System.out.println(byteBuf.getCharSequence(0, 4, CharsetUtil.UTF_8));
}
}
}