Using LINQ, need help splitting a byte array on data received from Silverlight sockets
Posted
by gcadmes
on Stack Overflow
See other posts from Stack Overflow
or by gcadmes
Published on 2010-05-18T19:57:08Z
Indexed on
2010/05/18
20:00 UTC
Read the original article
Hit count: 153
The message packats received contains multiple messages deliniated by a header=0xFD and a footer=0xFE
// sample message packet with three
// different size messages
List<byte> receiveBuffer = new List<byte>();
receiveBuffer.AddRange(new byte[]
{ 0xFD, 1, 2, 0xFE,
0xFD, 1, 2, 3, 4, 5, 6, 7, 8, 0xFE,
0xFD, 33, 65, 25, 44, 0xFE});
// note: this sample code is without synchronization,
// statements, error handling...etc.
while (receiveBuffer.Count > 0)
{
var bytesInRange = receiveBuffer.TakeWhile(n => n != 0xFE);
foreach (var n in bytesInRange)
Console.WriteLine(n);
// process message..
// 1) remove bytes read from receive buffer
// 2) construct message object...
// 3) etc...
receiveBuffer.RemoveRange(0, bytesInRange.Count());
}
As you can see, (including header/footer) the first message in this message packet contains 4 bytes, and the 2nd message contains 10 bytes,a and the 3rd message contains 6 bytes.
In the while loop, I was expecting the TakeWhile to add the bytes that did not equal the footer part of the message.
Note: Since I am removing the bytes after reading them, the header can always be expected to be at position '0'.
I searched examples for splitting byte arrays, but non demonstrated splitting on arrays of unknown and fluctuating sizes.
Any help will be greatly appreciated. thanks much!
© Stack Overflow or respective owner