Netty 提供一個專門用來操作緩沖區(即Netty的數據容器)的工具類:io.netty.buffer.Unpooled
之前簡單用過,如下:
/** * 通道就緒事件 * * @param ctx * @throws Exception */ @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { log.info("ClientHandler ctx: " + ctx); ctx.writeAndFlush(Unpooled.copiedBuffer("hello, 服務器!", CharsetUtil.UTF_8)); }
查看AbstractByteBuf 有三個屬性,
readerIndex 下次讀取的下標
writerIndex 下次寫入時的下標
maxCapacity 容量
通過 readerindex 和 writerIndex 和 capacity, 將buffer分成三個區域:
0---readerindex 已經讀取的區域;readerindex---writerIndex , 可讀的區域;writerIndex -- capacity, 可寫的區域。
1. 測試一
package netty; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; 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 buffer = Unpooled.buffer(10); for (int i = 0; i < 10; i++) { buffer.writeByte(i); } System.out.println("capacity=" + buffer.capacity());//10 //輸出 // for(int i = 0; i<buffer.capacity(); i++) { // System.out.println(buffer.getByte(i)); // } for (int i = 0; i < buffer.capacity(); i++) { System.out.println(buffer.readByte()); } System.out.println("執行完畢"); } }
結果:
capacity=10
0
1
2
3
4
5
6
7
8
9
執行完畢
2. 測試類2:
package netty; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import java.nio.charset.Charset; 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=" + byteBuf); System.out.println(byteBuf.arrayOffset()); // 0 System.out.println(byteBuf.readerIndex()); // 0 System.out.println(byteBuf.writerIndex()); // 12 System.out.println(byteBuf.capacity()); // 36 //System.out.println(byteBuf.readByte()); // System.out.println(byteBuf.getByte(0)); // 104 int len = byteBuf.readableBytes(); //可讀的字節數 12 System.out.println("len=" + len); //使用for取出各個字節 for (int i = 0; i < len; i++) { System.out.println((char) byteBuf.getByte(i)); // 強行轉為字符串,否則會直接打印ASCII碼 } //按照某個范圍讀取 System.out.println(byteBuf.getCharSequence(0, 4, Charset.forName("utf-8"))); System.out.println(byteBuf.getCharSequence(4, 6, Charset.forName("utf-8"))); } } }
結果:
hello,world! byteBuf=UnpooledByteBufAllocator$InstrumentedUnpooledUnsafeHeapByteBuf(ridx: 0, widx: 12, cap: 36) 0 0 12 36 104 len=12 h e l l o , w o r l d ! hell o,worl