I have a file transfer application (large files) and I want to make it so that it’s extensible. I use async callbacks to read the messages in chunks of 16Kb. Whenever I receive a message, I send it to a class that will “decypher” it and handle it. The format used is simple: (int)Command->(int)MsgLen->(String)Msg.
This is just one example. The problem I’m having is if I want to do multiple reads, what’s the best way to handle this? What happens if there are multiple commands in 1 read? For example I get near the end and I only have 2 bytes for the command as opposed to the full 4?
I thought of a queue but it’s a pain to extract the bytes and convert them. Any better options?
The simplest way is just keep a
byte[]array (or similar data structure) of all outstanding data. Always append to that array when new data arrives and then remove only the fully received messages.The only thing you’ll need to worry about is if you receive a message while another is being processed – so you’ll need to lock around the operations on the
byte[]array.There are more “clever” ways to go about this but for most situations the simplest method is the best.