網絡通信中,數據的獲取有時候並不按照你的想法進行,想每一次獲取的都是完整的數據幀,但是得到的卻是殘缺的幀,一個完整的幀分成幾段獲取到,或者一次獲取幾個完整幀。如何取得我們要處理的完整的幀,使用循環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;
}
}
// 處理取出來的一幀數據
........................
}
else
{
indexTemp++;
if (indexTemp == cycleBuffer.Length)
{
indexTemp = 0;
}
}
}