How to detect when a Protocol Buffer message is fully received?

后端 未结 4 1617
再見小時候
再見小時候 2020-12-30 13:35

This is kind of a branch off of my other question. Read it if you like, but it\'s not necessary.

Basically, I realized that in order to effectively use C#\'s BeginRe

4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-30 14:11

    You need to include the size or end marker in your protocol. Nothing is built into stream based sockets (TCP/IP) other than supporting an indefinite stream of octets arbitrarily broken up into separate packets (and packets can be spilt in transit as well).

    A simple approach would be for each "message" to have a fixed size header, include both a protocol version and a payload size and any other fixed data. Then the message content (payload).

    Optionally a message footer (fixed size) could be added with a checksum or even a cryptographic signature (depending on your reliability/security requirements).

    Knowing the payload size allows you to keep reading a number of bytes that will be enough for the rest of the message (and if a read completes with less, doing another read for the remaining bytes until the whole message has been received).

    Having a end message indicator also works, but you need to define how to handle your message containing that same octet sequence...

提交回复
热议问题