I'm creating a socket based system for communicating between desktop and mobile devices. I'm using a simple protocol for reading and writing data to the streams between devices which ultimately end up as bytes:
- First 4 bytes represent an integer, which defines a type of command to be executed
- Next 4 bytes represent an integer, which is the length of the rest of the bytes in the stream
- The remaining bytes represent the payload data, the total number of which corresponds to the result of (2.)
I'm able to successfully strip off the first 4 bytes and resolve the command ok, then strip off the next 4 bytes and resolve the length correctly. The problem comes when I strip off the remaining bytes, some of them are missing, and they're missing from the front of the remaining data.
For example; if the command is 1, and the length is 50, then there should be 50 bytes left in the stream but there's only 46 and it's bytes 0-3 which are missing.
The starting data is as follows:
- command: 1
- length: 50
- payload: C:\Users\dave\Music\Offaiah-Trouble_(Club_Mix).mp3
After converting this to a byte array, I get:
"\u0001\0\0\02\0\0\0C:\Users\dave\Music\Offaiah-Trouble_(Club_Mix).mp3"
(Question - why does the first integer get \u000 in front of it and the second does not?)
Here's some snippets of the code I'm using to parse this:
IBuffer inbuffer = new Windows.Storage.Streams.Buffer(4);
await _socket.InputStream.ReadAsync(inbuffer, 4, InputStreamOptions.None);
int command = BitConverter.ToInt32(inbuffer.ToArray(), 0);
The inbuffer at this point contains: "\u0001\0\0\0", and the BitConverter resolves this to 1
inbuffer = new Windows.Storage.Streams.Buffer(4);
await _socket.InputStream.ReadAsync(inbuffer, 4, InputStreamOptions.None);
int length = BitConverter.ToInt32(inbuffer.ToArray(), 0);
The inbuffer now contains: "2\0\0\0", and the BitConverter resolves this to "50"
inbuffer = new Windows.Storage.Streams.Buffer((uint)length);
await _socket.InputStream.ReadAsync(inbuffer, (uint)length, InputStreamOptions.Partial);
string path = Encoding.UTF8.GetString(inbuffer.ToArray());
The inbuffer now contains: "sers\dave\Music\Offaiah-Trouble_(Club_Mix).mp3"
Where did the missing "C:\U" go from the front of this?