• Netty(一):ByteBuf读写过程图解


    我们知道ByteBuf通过读写两个索引分离,避免了NIO中ByteBuffer中读写模式切换时,需要flip等繁琐的操作。

    今天就通过一段测试代码以及图例来直观的了解下ByteBuf中的readIndex, writeIndex以及capacity的概念。

    先贴出测试代码:

     1 public class ByteBuffTest {
     2 
     3     public static void main(String[] args){
     4         /*******************初始阶段**********************/
     5         ByteBuf buf = Unpooled.buffer(100, 200);
     6         System.out.println("writable bytes " + buf.writableBytes());
     7         System.out.println("readable bytes " + buf.readableBytes());
     8 
     9         /*******************写入数据**********************/
    10         String str = "write test";//UTF-8 英文字符占一个字节
    11         int length = str.getBytes().length;//因此得到的字节长度为10
    12         buf.writeBytes(str.getBytes());
    13         System.out.println("writable bytes " + buf.writableBytes());
    14         System.out.println("readable bytes " + buf.readableBytes());
    15 
    16         /*******************读取数据*********************/
    17         char c = (char)buf.readByte();//读取第一个字节,并转换成字符打印
    18         System.out.println("c:" + c);
    19         System.out.println("writable bytes " + buf.writableBytes());
    20         System.out.println("readable bytes " + buf.readableBytes());
    21 
    22         /*******************丢弃已读*********************/
    23         buf.discardReadBytes();
    24         System.out.println("writable bytes " + buf.writableBytes());
    25         System.out.println("readable bytes " + buf.readableBytes());
    26 
    27     }
    28 }

    然后是测试打印结果:

    对上述过程用图例直观表示:

  • 相关阅读:
    oracle恢复被覆盖的存储过程
    POJ 2478 Farey Sequence
    java不求有功,但求无过—异常处理
    图论-树的最大路
    MP3的频率、比特率、码率与音质的关系
    基于Lucene3.5.0怎样从TokenStream获得Token
    Groovy新手教程
    Binder机制1---Binder原理介绍
    UVA
    Hibernate Criterion
  • 原文地址:https://www.cnblogs.com/insaneXs/p/9303652.html
Copyright © 2020-2023  润新知