In network communication, data acquisition is sometimes not based on your ideas. Every time you get a complete data frame, you get a broken frame, A complete frame can be obtained in several segments, or several complete frames can be obtained at a time. How to obtain the complete frame to be processed and use the cyclic buffer can solve this problem.
[Csharp]
// Cyclic buffer for receiving and processing data
Byte [] receiveBuffer = new Byte [16]; // data receiving slowdown
Byte [] cycleBuffer = new Byte [1024]; // used to save data
Byte [] frameBuffer = new Byte [16]; // The frame obtained from cycleBuffer
Int32 receiveCount; // number of received data
Int32 indexHead, indexTail; // header pointer, tail pointer
IndexHead = indexTail = 0;
// Cyclic buffer for receiving and processing data
Byte [] receiveBuffer = new Byte [16]; // data receiving slowdown
Byte [] cycleBuffer = new Byte [1024]; // used to save data
Byte [] frameBuffer = new Byte [16]; // The frame obtained from cycleBuffer
Int32 receiveCount; // number of received data
Int32 indexHead, indexTail; // header pointer, tail pointer
IndexHead = indexTail = 0;
[Csharp]
// Put the received data in the cyclic buffer.
For (int I = 0; I <receiveCount; I ++)
{
IndexTail ++;
If (indexTail = cycleBuffer. Length)
{
IndexTail = 0;
}
CycleBuffer [indexTail] = receiveBuffer [I];
}
// Put the received data in the cyclic buffer.
For (int I = 0; I <receiveCount; I ++)
{
IndexTail ++;
If (indexTail = cycleBuffer. Length)
{
IndexTail = 0;
}
CycleBuffer [indexTail] = receiveBuffer [I];
}
[Csharp]
// Start to get the frame in the loop buffer-specify the string
Int32 indexTemp = indexHead;
While (indexTemp! = IndexTail)
{
If (cycleBuffer [indexTemp] = (Byte) '$') // locate the frame
{
Int32 dec = 0;
While (indexHead! = IndexTemp)
{
FrameBuffer [dec ++] = cycleBuffer [indexHead];
IndexHead ++;
If (indexHead = cycleBuffer. Length)
{
IndexHead = 0;
}
}
// Process the retrieved frame of data
........................
}
Else
{
IndexTemp ++;
If (indexTemp = cycleBuffer. Length)
{
IndexTemp = 0;
}
}
}
// Start to get the frame in the loop buffer-specify the string
Int32 indexTemp = indexHead;
While (indexTemp! = IndexTail)
{
If (cycleBuffer [indexTemp] = (Byte) '$') // locate the frame
{
Int32 dec = 0;
While (indexHead! = IndexTemp)
{
FrameBuffer [dec ++] = cycleBuffer [indexHead];
IndexHead ++;
If (indexHead = cycleBuffer. Length)
{
IndexHead = 0;
}
}
// Process the retrieved frame of data
........................
}
Else
{
IndexTemp ++;
If (indexTemp = cycleBuffer. Length)
{
IndexTemp = 0;
}
}
}