i'm using a C# thread to handle incoming TCP data.
The data has a predefined format, e.g.
Hex: A1 B1 01 03 data... 0C 0E
where A1 B1 are to sync byte (which are always the same)
List 03 is the message length
and 0C 0E are two trailing bytes (which are always the same)
if this data is always in one TCP Package it is now problem to handle the data.
while (connection.Available < 4)
{
}
before = connection.Available;
nStream.Read(Buffer_Sync_length, 0, 4);
after = connection.Available;
if ((Buffer_Sync_length[0] == 0xA1) && (Buffer_Sync_length[1] == 0xB1))
{
int length = Buffer_Sync_length[3];
while (connection.Available < (length + 2))
{ }
nStream.Read(inBuffer, 0, length+2);
Array.Clear(rec_Buffer, 0, inBuffer.Length);
Array.Copy(Buffer_Sync_length, rec_Buffer, 4);
Array.Copy(inBuffer, 0, rec_Buffer, 4, length);
transmit(rec_Buffer);
Array.Clear(Buffer_Sync_length, 0, Buffer_Sync_length.Length);
Array.Clear(inBuffer, 0, inBuffer.Length);
Array.Clear(rec_Buffer, 0, rec_Buffer.Length);
}
which runs in a thread.
But sometimes the data is splitted randomly into TCP packages. Then the sync byte position is different in the buffer.
I have thought about a ring buffer where the data is written to and constantly searched for the Sync bytes.
What is the best way to implement it? Or do you have other suggestions?
Greets, Andi