在网络编程中,我们会频繁用到两个东西,一个是buffer。一个是bit-order。把数据填充到buffer中,然后通过buffer读写我们所需要的基本数据,还好.NET为我们提供了BitConverter这个非常好用的util,方便我们编写自己的Buffer和字节序转换器。
IBuffer
通常Buffer会有如下几个概念;position,limit,capacity,flip,mark,reset,free
position:即将读/写的位置
limit:有效读/写的极限位置
capacity:buffer的最大长度
flip:limit设为置position,position设为0
mark:记录当前的position,对应reset操作
reset:将position设置为之前mark的位置
free:将缓冲标识为空闲,可在入池前调用。
比如,一个capacity为6的缓冲区,加入当前position为0,那么下次读/写操作都将从0位置开始。
我read 2个字节,读出的是2和-1,此时position会变成2,再write 4个字节的数据,将从位置2开始,将这4个字节的数据写到byte[2]-byte[5]中,最后position为6,如果再继续读/写,除非缓冲设置为AutoExpand否则将会发生缓冲区益处。
下面是我自己的IBuffer接口和一个IBuffer的实现,如果您没用过BitConverter、Buffer建议您查阅MSDN,这里就不再复述。
使用说明:a.将AutoExtend设置为true,FastBuffer会在预知缓冲大小不够的情况下自动扩展,如果设置为false,一旦读/写操作超出capacity大小会抛出BufferOverflowException。b.如果想预分配n个字节的缓冲,只需:FastBuffer.Allocate(n)。c.如果想将一个byte[] data放在FastBuffer中只需调用FastBuffer.Wrap(data)。
FastBuffer:
public interface IBuffer
: IDataReader, IDataWriter
{
int Position { get; set; }
int Limit { get; set; }
int Capacity { get; set; }
void Flip();
void Rewind();
void Clear();
void Reset();
void Free();
long Remaining { get; }
byte[] toAllBytes();
byte[] copyAvaliableBytes();
bool AutoExtend { get; set; }
void Append(byte[] p, int start, int length);
}