3
votes

I'm playing with some asynchronous TCP socket server code that I found at MSDN and I'm unclear on how to detect that I've received all the data that a client is supposed to send. In the MSDN example, they're sending ASCII strings (converted to bytes, of course) and after each read of the socket, they check to see if the decoded string contains an EOF marker. If it does not, the code calls BeginReceive() again to retrieve more data.

The client that I'm receiving data from will send one of 8 different binary "messages" (not ASCII strings). These byte arrays can vary in length from 6 bytes to ~10KB. My read buffer is 1KB so there's a decent chance that I'll need to call BeginReceive() several times in order to read all of the data. Does the client need to embed the total length of the byte array somewhere near the beginning of the array in order for me to determine that all the data has all been received?

1
If the client is sending multiple "messages" on the same connection, the protocol will have to have some indication of how to break them up. That could be something indicating "end of message" or (simpler) a length prefix on each message. It's not clear whether you control the protocol or not though... - Jon Skeet
@Jon Skeet - thanks for the confirmation. And yes, I do have control over the protocol so I'll probably just add a length prefix to each message. - bmt22033

1 Answers

4
votes

If you're designing this binary protocol, it's up to you how the end of message will be marked and determined. Embedding the length in the beginning of the message is a common way to do this. If someone else designed the protocol, ask them how the end of message is marked and determined. It's a protocol design decision.