.NET question about asynchronous socket operations and message framing

前端 未结 3 1141
长发绾君心
长发绾君心 2021-01-12 00:13

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

3条回答
  •  旧时难觅i
    2021-01-12 00:59

    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.

提交回复
热议问题