码迷,mamicode.com
首页 > 编程语言 > 详细

设计一个字节数组缓存类

时间:2015-03-17 00:24:04      阅读:227      评论:0      收藏:0      [点我收藏+]

标签:

转 http://blog.csdn.net/kakashi8841/article/details/42025367

版权所有,转载须注明出处!

1、为什么要

在做网络通信的时候,经常需要用到:

  • 读:就是我们需要从网络流里面读取字节数据,并且由于分包的原因,我们需要自己缓存这些数据,而不是读完立刻丢掉。
  • 写:我们需要把各种类型的数据变成字节写入。比如把int、string、short等变成字节数组写入流。

 

2、需要什么

我们需要设计一个类来实现:

  • 支持可以不停地往这个类中添加字节
  • 支持写入int、string、short等基础数据类型
  • 支持从这个类中获取可读的字节

3、怎么做

    1. 支持可以不停地往这个类中添加字节

    这个实现你可以用一个List<byte>来实现(本身List就支持无限往里面添加元素)。不过由于这个类比较特殊。处于网络最底层,使用比较频繁。因此我们还是自己用byte[]来处理。

    2.支持写入int、string、short等基础数据类型

    这个简单,在实现了上一步添加字节数组的基础上,剩下的只需要把各种数据类型编码成byte数组而已。比如一个int变成用4个byte表示。

    3.支持从这个类中获取可读的字节

    比如你写入了10个byte,那么肯定需要能从里面读出这10个byte。不然写入的数据就没意义了。

4、开始动手写代码

 

[csharp] view plaincopy技术分享技术分享
  1. <span style="font-family:Microsoft YaHei;">using System;  
  2. using System.Text;  
  3.    
  4. namespace com.duoyu001.net  
  5. {  
  6.     namespace buffer  
  7.     {  
  8.         /* ============================================================================== 
  9.              * 功能描述:字节缓冲类 
  10.              * 创 建 者:cjunhong 
  11.              * 主    页:http://blog.csdn.net/kakashi8841 
  12.              * 邮    箱:[url=mailto:john.cha@qq.com]john.cha@qq.com[/url] 
  13.              * 创建日期:2014/12/02 16:22:09 
  14.              * ==============================================================================*/  
  15.    
  16.         public class ByteBuffer  
  17.         {  
  18.             //增加的容量  
  19.             public const short CAPACITY_INCREASEMENT = 128;  
  20.             public const ushort USHORT_8 = (ushort) 8;  
  21.             public const short SHORT_8 = (short) 8;  
  22.             //字节数组  
  23.             private byte[] buffers;  
  24.             //读取索引  
  25.             private int readerIndex;  
  26.             //写的索引  
  27.             private int writerIndex;  
  28.             //上次备份的reader索引  
  29.             private int readerIndexBak;  
  30.             //字符数组 空字符串  
  31.             public static byte[] NULL_STRING = new byte[] {(byte) 0, (byte) 0};  
  32.    
  33.             public ByteBuffer()  
  34.                 : this(8)  
  35.             {  
  36.             }  
  37.    
  38.             /// <summary>  
  39.             /// 带参构造函数 初始化字节数组  
  40.             /// </summary>  
  41.             /// <param name="initCapacity">初始容量</param>  
  42.             public ByteBuffer(int initCapacity)  
  43.             {  
  44.                 buffers = new byte[initCapacity];  
  45.             }  
  46.    
  47.             /// <summary>  
  48.             /// 带参构造函数 向字节数组中 写字节  
  49.             /// </summary>  
  50.             /// <param name="buffers">字节数组</param>  
  51.             public ByteBuffer(byte[] buffers)  
  52.                 : this(buffers.Length)  
  53.             {  
  54.                 writeBytes(buffers);  
  55.             }  
  56.    
  57.             public void writeBytes(byte[] data, int dataOffset, int dataSize)  
  58.             {  
  59.                 ensureWritable(dataSize);  
  60.                 Array.Copy(data, dataOffset, buffers, writerIndex, dataSize);  
  61.                 writerIndex += dataSize;  
  62.             }  
  63.    
  64.             public void writeBytes(byte[] data)  
  65.             {  
  66.                 writeBytes(data, 0, data.Length);  
  67.             }  
  68.    
  69.             public void writeByte(byte data)  
  70.             {  
  71.                 writeBytes(new byte[] {data});  
  72.             }  
  73.    
  74.             public void writeByte(int data)  
  75.             {  
  76.                 writeBytes(new byte[] {(byte) data});  
  77.             }  
  78.    
  79.             public void writeShort(int data)  
  80.             {  
  81.                 writeBytes(new byte[] {(byte) (data >> 8), (byte) data});  
  82.             }  
  83.    
  84.             public void writeInt(int data)  
  85.             {  
  86.                 writeBytes(new byte[]  
  87.                     {  
  88.                         (byte) (data >> 24),  
  89.                         (byte) (data >> 16),  
  90.                         (byte) (data >> 8),  
  91.                         (byte) data  
  92.                     });  
  93.             }  
  94.    
  95.             public void writeString(string data)  
  96.             {  
  97.                 writeString(data, Encoding.UTF8);  
  98.             }  
  99.    
  100.             public void writeString(string data, Encoding encoding)  
  101.             {  
  102.                 if (data == null)  
  103.                 {  
  104.                     writeBytes(NULL_STRING);  
  105.                 }  
  106.                 else  
  107.                 {  
  108.                     byte[] b = encoding.GetBytes(data);  
  109.                     byte[] strBytes = new byte[b.Length + 2];  
  110.                     strBytes[0] = (byte) ((b.Length & 0xff00) >> 8);  
  111.                     strBytes[1] = (byte) (b.Length & 0xff);  
  112.                     b.CopyTo(strBytes, 2);  
  113.                     writeBytes(strBytes);  
  114.                 }  
  115.             }  
  116.    
  117.             public byte readByte()  
  118.             {  
  119.                 byte b = buffers[readerIndex];  
  120.                 readerIndex++;  
  121.                 return b;  
  122.             }  
  123.    
  124.             public ushort readUnsignShort()  
  125.             {  
  126.                 ushort u = (ushort) (buffers[readerIndex] << USHORT_8 | buffers[readerIndex + 1]);  
  127.                 readerIndex += 2;  
  128.                 return u;  
  129.             }  
  130.    
  131.             public short readShort()  
  132.             {  
  133.                 short i = (short) (buffers[readerIndex] << SHORT_8 | buffers[readerIndex + 1]);  
  134.                 readerIndex += 2;  
  135.                 return i;  
  136.             }  
  137.    
  138.             public int readInt()  
  139.             {  
  140.                 int i = buffers[readerIndex] << 24 | buffers[readerIndex + 1] << 16 | buffers[readerIndex + 2] << 8 |  
  141.                         buffers[readerIndex + 3];  
  142.                 readerIndex += 4;  
  143.                 return i;  
  144.             }  
  145.    
  146.             public uint readUnsignInt()  
  147.             {  
  148.                 return (uint) readInt();  
  149.             }  
  150.    
  151.             public byte[] readBytes(int length)  
  152.             {  
  153.                 byte[] b = new byte[length];  
  154.                 Array.Copy(buffers, readerIndex, b, 0, length);  
  155.                 readerIndex += length;  
  156.                 return b;  
  157.             }  
  158.    
  159.             public string readString()  
  160.             {  
  161.                 return readString(Encoding.UTF8);  
  162.             }  
  163.    
  164.             public string readString(Encoding encoding)  
  165.             {  
  166.                 ushort charLength = readUnsignShort();  
  167.                 byte[] strBytes = readBytes(charLength);  
  168.                 return encoding.GetString(strBytes);  
  169.             }  
  170.    
  171.             public void writeBuffer(ByteBuffer buff)  
  172.             {  
  173.                 byte[] bytes = buff.readBytes(buff.readableBytes());  
  174.                 writeBytes(bytes);  
  175.             }  
  176.    
  177.             public ByteBuffer readBuffer(int length)  
  178.             {  
  179.                 byte[] bytes = readBytes(length);  
  180.                 return new ByteBuffer(bytes);  
  181.             }  
  182.    
  183.             public byte[] toArray()  
  184.             {  
  185.                 return readBytes(readableBytes());  
  186.             }  
  187.    
  188.             public byte[] getBytes()  
  189.             {  
  190.                 return buffers;  
  191.             }  
  192.    
  193.             public int readableBytes()  
  194.             {  
  195.                 return writerIndex - readerIndex;  
  196.             }  
  197.    
  198.             public void saveReaderIndex()  
  199.             {  
  200.                 readerIndexBak = readerIndex;  
  201.             }  
  202.    
  203.             public void loadReaderIndex()  
  204.             {  
  205.                 readerIndex = readerIndexBak;  
  206.             }  
  207.    
  208.             private void ensureWritable(int dataSize)  
  209.             {  
  210.                 int leftCapacity = buffers.Length - writerIndex;  
  211.                 if (leftCapacity < dataSize)  
  212.                 {  
  213.                     int oldReaderIndex = readerIndex;  
  214.                     int oldWriterIndex = writerIndex;  
  215.                     writerIndex = readableBytes();  
  216.                     readerIndex = 0;  
  217.                     if (buffers.Length - writerIndex >= dataSize)  
  218.                     {  
  219.                         Array.Copy(buffers, oldReaderIndex, buffers, 0, oldWriterIndex - oldReaderIndex);  
  220.                     }  
  221.                     else  
  222.                     {  
  223.                         byte[] newBuffers = new byte[buffers.Length + CAPACITY_INCREASEMENT];  
  224.                         Array.Copy(buffers, oldReaderIndex, newBuffers, 0, oldWriterIndex - oldReaderIndex);  
  225.                         buffers = newBuffers;  
  226.                     }  
  227.                 }  
  228.             }  
  229.    
  230.             public int getReaderIndex()  
  231.             {  
  232.                 return readerIndex;  
  233.             }  
  234.    
  235.             public int getWriterIndex()  
  236.             {  
  237.                 return writerIndex;  
  238.             }  
  239.    
  240.             public int getCapacity()  
  241.             {  
  242.                 return buffers.Length;  
  243.             }  
  244.    
  245.             public string remainBufferString()  
  246.             {  
  247.                 string s = "";  
  248.                 for (int i = readerIndex; i < writerIndex; i++)  
  249.                 {  
  250.                     s += buffers;  
  251.                     if (i < writerIndex - 1)  
  252.                     {  
  253.                         s += ", ";  
  254.                     }  
  255.                 }  
  256.                 return s;  
  257.             }  
  258.         }  
  259.     }  
  260. }</span>  

5、怎么用

1、怎么写数据

    比如你想写入一个int。那么只要调用writeInt方法。想写入short、byte、string等 只要调用相应的writeShort、writeByte、writeString等方法即可。

2、怎么读数据

    比如你想读出一个int。那么只要调用readInt方法。相应读取short、byte、string等 也只要调用readShort、readByte、readString等方法。

3、怎么记录上次读取位置,并重置当前的位置到上次位置

    比如你想读取一个数据,然后判断数据是否符合期望值,如果不符合则返回到读取前状态。(这个在处理分包的时候经常需要用到,因为你需要确认本次想读取的数据是否已经全部接受完,如果还没接受完,那么你就需要等到下次接受完整再来读取)那么只要这么调用:
        saveReaderIndex
        readXXX
        loadReaderIndex


6、内部设计说明

1、关于writeXXX

    可以看到。writeInt、writeShort、writeByte、writeString等方法,都是调用writeBytes(byte[] data)。没错,正如上面说的,各种写方法,只是把指定的数据类型编码成byte数组,然后添加到里面而已。

       1.1、怎么编码

        比如writeInt,其实只是简单用移位获取它每个8位的的数据(一个int是由4个byte组成的嘛-_-)。然后就writeBytes(byte[] data)

       1.2、writeBytes做了啥

public void writeBytes(byte[] data, int dataOffset, int dataSize)
{
    ensureWritable(dataSize);
    Array.Copy(data, dataOffset, buffers, writerIndex, dataSize);
    writerIndex += dataSize;
}
上面说了,我们要支持能无限往里面写数据。因此,第一行代码ensureWritable就是来确定当前是否能写入指定长度的数据。如果判断不行,则会进行扩容(怎样判断具体的思路我们在后面会说)。
        第二行代码则是把写入的数据复制到我们这个缓存对象上的指定位置。
        第三行则是把写指针writeIndex往后移。
        细心的读者应该会发现ensureWritable中有关于readerIndex、writerIndex这些参数的一些计算。接着看下面。


2、读写指针readerIndex与writerIndex

    我们使用byte[]数组来保存数据,那么我们怎么知道如果追加数据的时候,应该把新数据加入到数组中的哪个位置?怎么知道当前有多少数据可以读?有多少空间可以写入数据?

        2.1、writerIndex

        我们使用writerIndex来记录当前数组中哪个位置可以开始写入数据。最开始这个值为0,每当写入一个byte的时候,这个值加1。(请看上面1.2中writeBytes的第三行代码)

        2.2、readerIndex

        缓冲区的数据是读取之后就会丢弃的,但是如果每次读取就要重建数组来实现丢弃,这样的开销就太大了。因此,我们可以使用readerIndex来记录当前读取到数组中哪个位置,那么下次读取就会从这个位置开始读取数据了。每当读取一个byte,readerIndex加1。你可以先看看下面这段readInt的代码,读取了一个int(4个byte),那么readerIndex会增加4。
public int readInt()
{
    int i = buffers[readerIndex] << 24 | buffers[readerIndex + 1] << 16 | buffers[readerIndex + 2] << 8 |
            buffers[readerIndex + 3];
    readerIndex += 4;
    return i;
}

        2.3、writerIndex和readerIndex的关系

        怎样判断当前有多少数据可以读?根据上面对这两个参数的解释,我们可以轻易得出问题的答案是:writerIndex-readerIndex。这也正是readableBytes方法中的实现。
public int readableBytes()
{
    return writerIndex - readerIndex;
}

       2.4、怎样判断当前有没有足够的空间来写入数据

        最简单的方法是:判断数据剩余写入空间是否大于要写入的数据长度。剩余写入空间即:buffers.Length - writerIndex
        当时如果上面判断出的剩余写入空间比要写入的数据长度小时,是否就要重建一个更大的数组呢?不一定,因为还可以回收一些已经读取过的空间来使用。具体代码:
private void ensureWritable(int dataSize)
{
    int leftCapacity = buffers.Length - writerIndex;
    if (leftCapacity < dataSize)
    {
        int oldReaderIndex = readerIndex;
        int oldWriterIndex = writerIndex;
        writerIndex = readableBytes();
        readerIndex = 0;
        if (buffers.Length - writerIndex >= dataSize)
        {
            Array.Copy(buffers, oldReaderIndex, buffers, 0, oldWriterIndex - oldReaderIndex);
        }
        else
        {
            byte[] newBuffers = new byte[buffers.Length + CAPACITY_INCREASEMENT];
            Array.Copy(buffers, oldReaderIndex, newBuffers, 0, oldWriterIndex - oldReaderIndex);
            buffers = newBuffers;
        }
    }
}
       可以看到,当满足buffers.Length - writerIndex >= dataSize条件时,是没有重建数组的。因为这时候说明你前面有一些读取过的数据,因此你只需要把那部分读取过的数据丢弃掉,就有更多的空间来容纳要写入的数据了。

        2.5、这个类还有个readerIndexBak的又是干嘛的?  

       前面说了,你有时候需要进行尝试数据读取,但是当发现没到读取时间的时候,想要恢复读取状态,就可以通过在读取前保存读取指针,后面可以恢复读取指针。


基本关于这个类在Socket通信中使用已经足够满足大部分应用场景的需要了。
至于你说你用Protobuf或什么之类的协议。和这个类是无关的。比如:读取的时候只要这个对象中读取byte字节,然后反序列化成Protobuf数据即可。
反正这个类是通信中最基础的一个数据类。有需要的就拿去吧~

设计一个字节数组缓存类

标签:

原文地址:http://www.cnblogs.com/lihonglin2016/p/4343179.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!