Click here to Skip to main content
15,888,330 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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.

C#
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
Posted
Comments
gggustafson 29-Apr-14 11:01am    
Are there any byte values that can not appear in a packet (e.g., FF, FE, etc)? If so, you could reduce the message length. Say you can use FE, then your stream could become FE03010203FE.... You do not need to process an end-of-message byte(s). This requires the circular buffer you mentioned.
Sergey Alexandrovich Kryukov 29-Apr-14 11:03am    
You say "hex"... does it mean that you are sending/receiving characters, instead of numbers? Why? Or is your "hex" just notation you use to ask the question?
—SA

1 solution

Yes, you could use a circular buffer, however you could as well take advantage from the protocol (size of data is gently provided) for asking just the needed bytes.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900