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