Data exchange via TCP. Ensure that the message is complete.

Noah Aas 1,110 Reputation points
2025-10-24T14:52:51.9+00:00

I have a question—answer interface to implement. If the message is large, it may be split into several parts. What options are available for receiving complete messages?

Request

<ROOT>
  <REQUESTS>
    <VARIANT name="Receiver">
      <PROGRAM name="824842" />
    </VARIANT>
    <VARIANT name="Color">
      <PROGRAM name="9d9.88" />
      <PROGRAM name="9s9.88" />
    </VARIANT>
  </REQUESTS>
</ROOT>

Response

<ROOT>
  <RESPONSE>
    <CURRENT name="Receiver">
      <PRODUCT name="MusicDAB_99" />
    </CURRENT>
   </RESPONSE>
</ROOT>
if (data.Length > 0)
 {
     string receivedMessage = messageBuilder.ToString().TrimEnd();

     // Raise the MessageReceived event
     OnMessageReceived($"{client.Client.RemoteEndPoint}: {receivedMessage}");

     receivedMessage = "From  24.10.2025, " + receivedMessage;
     byte[] response = Encoding.ASCII.GetBytes(receivedMessage.ToUpper() + Environment.NewLine);
     await stream.WriteAsync(response, 0, response.Length);

     messageBuilder.Clear();
 }
Developer technologies | C#
Developer technologies | C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 81,191 Reputation points Volunteer Moderator
    2025-10-24T16:35:21.8266667+00:00

    TCP data is passed as a stream read as packets. You need to be able to detect the end of message. Often the message has a header which goes the size of the message. When you have read as many bytes as the message size you have the complete message. Additional bytes would be the next message.

    in your case it looks the message is xml. You know you’ve read the full message when the </ROOT> has been read. Again any bytes after are the next message. The best approach would be using a streaming xml parser so you can detect the end of the xml stream.


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.