I am using the server-client model for communicating with a hardware board using socket programing.
I receive data from board using “read()” method of “NetworkStream” class which reads a buffer with specified maximum size and returns the length of valid data in buffer. I have considered the maximum size of buffer with a enough big number.
The board sends a set of messages every 100ms. Each message consists a 2-byte constant header and a variable number of bytes as its data after the header bytes.
The problem is that I do not receive the messages one by one! Instead, I receive a buffer may contains 2 or 3 messages or one message is scattered between two buffer.
Currently, I am using a DFA which gather the content of messages using the constant header bytes (We do not know the length of messages, we just know the header bytes) but the problem is that the data bytes may contains the header bytes randomly !!
Is there any efficient way to gather the bytes of each message from buffers using any specific stream or class? How can I overcome to this problem?!
You need to add an additional buffer component between your consumer DFA and the socket client.
Whenever data is avaliable from the
NetworkStreamthe buffer component will read it and append it to its own private buffer, incrementing an “available bytes” counter. The buffer component needs to expose at least the following functionality to its users:BytesAvailableproperty — this returns the value of the counterPeekBytes(int count)method — this returns the firstcountbytes of the buffer, if that much is available at least, and does not modify the counter or the bufferReadBytes(int count)method — as above, but it decrements the counter bycountand removes the bytes read from the buffer so that subsequentPeekBytescalls will never read them againKeep in mind that you don’t need to be able to service an arbitrarily high
countparameter; it is enough if you can service acountas long as the longest message it would be possible to receive at all times.Obviously the buffer component needs to keep some kind of data structure that allows “wrapping around” of some kind; you might want to look into a circular (ring) buffer implementation, or you can just use two fixed buffers of size
NwhereNis the length of the longest message and switch from one to the other as they become full. You should be careful so that you stop pulling in data from theNetworkStreamif your buffers become full and only continue pulling after the DFA has calledReadBytesto free up some buffer space.Whenever your DFA needs to read data, it will first ask your buffer stage how much data it has accumulated and then proceed accordingly. It would look something like this:
This way your DFA will only ever deal with whole messages.