
On Wednesday, May 11, 2011 11:12 AM, Slav wrote:
And, by the way, there could come empty messages - just without any data.
TCP does not have a concept of an empty write.
TCP contains info about message length - it is duplication to prefix all messages with it's length.
Where did you read that? TCP has NO concept of "messages". As such, it has no concept of "message length". It is only a stream of bytes. The sending computer can easily combine the buffers from two consecutive write calls into a single packet, or split the buffer from a single write call into multiple packets, or both. In either case, ALL information about the size of the original write call(s), the number of write calls, and anything else that you hope will provide a clue about "messages" will be lost. Likewise, the receiving computer can and will freely combine and split packets into whatever buffers it sees fit, with similar effects on any "message boundaries". The only thing that will remain is the sequence of bytes. Do not try to search for TCP options to change this behavior. The closest you can come is options that will *usually* keep the message boundaries. This means that your program will *usually* not crash. If you wish to preserve message boundaries, then you MUST provide your own message framing, just as you would if writing to a file. If you prefix each message with its length, then you can use the read function to ensure you get the whole message in one call, as you will know the message length. This will also be effective at ensuring you don't have the beginning of the next message at the end of your buffer.