I\'ve been looking everywhere for examples on how to deal with TCP message framing. I see many examples where NetworkStreams are passed into a StreamReader or StreamWriter o
Basically you create a buffer, and each time you receive data, you add that data to the buffer and determine if you have already received one or more full messages.
Between ReceiveCallback
and StartRead
you won't receive any asynchronous messages (incoming data will automatically be buffered on the socket level) so it's the ideal place to check for full messages and remove them from the buffer.
All variations are possible, including receiving the end of message 1, plus message 2, plus the beginning of message 3, all in one chunk.
I don't recommend UTF8-decoding the chunk, as one UTF8-character may consist of two bytes, and if they get split between chunks your data could be corrupted. You could keep a byte[]-buffer (MemoryStream
?) and split messages on the 0x0A byte in that case.