Netty中讀寫以ByteBuf爲載體進行交互微信
ByteBuf byteBuf = Unpooled.copiedBuffer("hello world".getBytes()); //判斷是否有可讀的字節 System.out.println(byteBuf.isReadable()); //返回可讀字節數 System.out.println(byteBuf.readableBytes()); //返回當前的讀指針 System.out.println(byteBuf.readerIndex()); while (byteBuf.isReadable()) { //以read開頭的方法都是讀取方法,readInt、readBoolean等 byteBuf.readByte(); } System.out.println(byteBuf.readerIndex()); //設置讀指針 byteBuf.readerIndex(0); //將當前可讀數據都讀取到byte[]中 byteBuf.readBytes(new byte[byteBuf.readableBytes()]);
//分配capacity爲9,maxCapacity爲12的byteBuf ByteBuf byteBuf = ByteBufAllocator.DEFAULT.buffer(9, 12); //返回可寫字節數 System.out.println(byteBuf.writableBytes()); //判斷是否可寫 System.out.println(byteBuf.isWritable()); //以write開頭的都是寫入方法 byteBuf.writeByte(1); byteBuf.writeInt(1); byteBuf.writeBytes(new byte[]{1,2,3,4}); //獲取寫指針 System.out.println(byteBuf.writerIndex()); //這時writerIndex==capacity System.out.println(byteBuf.writableBytes()); System.out.println(byteBuf.isWritable()); //再寫入將擴容 byteBuf.writeByte(1); System.out.println(byteBuf.isWritable()); System.out.println(byteBuf.writableBytes()); //擴容後仍然不足存放將報錯 //byteBuf.writeInt(1); //設置寫指針 byteBuf.writerIndex(0); System.out.println(byteBuf.isWritable()); System.out.println(byteBuf.writableBytes()); byteBuf.writeInt(1);
release() 與 retain()
Netty實戰
Netty 入門與實戰:仿寫微信 IM 即時通信系統jvm