循环buffer解决网络通信中数据的不完整接收
网络通信中,数据的获取有时候并不按照你的想法进行,想每一次获取的都是完整的数据帧,但是得到的却是残缺的帧,一个完整的帧分成几段获取到,或者一次获取几个完整帧。如何取得我们要处理的完整的帧,使用循环buffer可以解决这个问题,分享给各位
[csharp]
// 循环buffer实现数据的接收以及处理
Byte[] receiveBuffer = new Byte[16]; // 数据接收缓区
Byte[] cycleBuffer = new Byte[1024]; // 用来保存数据
Byte[] frameBuffer = new Byte[16]; // 从cycleBuffer中得到的帧
Int32 receiveCount; // 接收到的数据数
Int32 indexHead, indexTail; // 头指针,尾指针
indexHead = indexTail = 0;
// 循环buffer实现数据的接收以及处理
Byte[] receiveBuffer = new Byte[16]; // 数据接收缓区
Byte[] cycleBuffer = new Byte[1024]; // 用来保存数据
Byte[] frameBuffer = new Byte[16]; // 从cycleBuffer中得到的帧
Int32 receiveCount; // 接收到的数据数
Int32 indexHead, indexTail; // 头指针,尾指针
indexHead = indexTail = 0;
[csharp]
// 将接收到的数据放到循环buffer中去
for (int i = 0; i < receiveCount; i++)
{
indexTail++;
if (indexTail == cycleBuffer.Length)
{
indexTail = 0;
}
cycleBuffer[indexTail] = receiveBuffer[i];
}
// 将接收到的数据放到循环buffer中去
for (int i = 0; i < receiveCount; i++)
{
indexTail++;
if (indexTail == cycleBuffer.Length)
{
indexTail = 0;
}
cycleBuffer[indexTail] = receiveBuffer[i];
}
[csharp]
// 开始在循环buffer中取帧--指定字串
Int32 indexTemp = indexHead;
while (indexTemp != indexTail)
{
if (cycleBuffer[indexTemp] == (Byte)'$') // 找到帧
{
Int32 dec = 0;
while (indexHead != indexTemp)
{
frameBuffer[dec++] = cycleBuffer[indexHead];
indexHead++;
if (indexHead == cycleBuffer.Length)
{
indexHead = 0;
}
}
// 处理取出来的一帧数据
........................
}
else
{
indexTemp++;
if (indexTemp == cycleBuffer.Length)
{
indexTemp = 0;
}
}
}
// 开始在循环buffer中取帧--指定字串
Int32 indexTemp = indexHead;
while (indexTemp != indexTail)
{
if (cycleBuffer[indexTemp] == (Byte)'$') // 找到帧
{
Int32 dec = 0;
while (indexHead != indexTemp)
{
frameBuffer[dec++] = cycleBuffer[indexHead];
indexHead++;
if (indexHead == cycleBuffer.Length)
{
indexHead = 0;
}
}
&nbs
补充:软件开发 , C# ,