Neither .NET nor the TCP protocol has anything built in to determine the size of the message that needs to be pre-configured. TCP only indicates that all data will be transmitted to the receiving endpoint (or at least the best efforts will be used for this).
You are solely responsible for determining how the recipient knows how much data to read. The details of how you do this, as others have pointed out, depend on the nature of what you are transmitting: you could send the length first, as you mentioned, you can encode special sequences called terminators, you could use predefined pieces of data therefore, all messages are the same size, etc.
EDIT
It began as a comment, but there is more than is suitable for this limit.
Adding NULL to a stream simply means adding a character that has a binary value of 0 (not to be confused with the character 0 ). Depending on the encoding that you use for your transfer (for example, ASCII, UTF-8, UTF-16, etc.), which can translate to send one or more 0 bytes, but if you use the appropriate translation, you just you need to put something like \0 in your line. Here is an example:
string textToSend = "This is a NULL Terminated text\0"; byte[] bufferToSend = Encoding.UTF8Encoding.GetBytes(textToSend);
Of course, all of the above assumes that all other data that you send does not contain any other NULLs. This means that it is text, not arbitrary binary data (for example, the contents of a file). It is very important! Otherwise, you cannot use NULL as a message terminator, and you will have to come up with a different scheme.
Mike dinescu
source share