c++clienttcpc++builder-5

Handling TCP Streams


Our server is seemingly packet based. It is an adaptation from an old serial based system. It has been added, modified, re-built, etc over the years. Since TCP is a stream protocol and not a packet protocol, sometimes the packets get broken up. The ServerSocket is designed in such a way that when the Client sends data, part of the data contains the size of our message such as 55. Sometimes these packets are split into multiple pieces. They arrive in order but since we do not know how the messages will be split, our server sometimes does not know how to identify the split message.

So, having given you the background information. What is the best method to rebuild the packets as they come in if they are split? We are using C++ Builder 5 (yes I know, old IDE but this is all we can work with at the moment. ALOT of work to re-design in .NET or newer technology).


Solution

  • TCP guarantees that the data will arrive in the same order it was sent.

    That beeing said, you can just append all the incoming data to a buffer. Then check if your buffer contains one or more packets, and remove them from the buffer, keeping all the remaining data into the buffer for future check.

    This, of course, suppose that your packets have some header that indicates the size of the following data.

    Lets consider packets have the following structure:

    [LEN] X X X...
    

    Where LEN is the size of the data and each X is an byte.

    If you receive:

    4 X X X
    [--1--]
    

    The packet is not complete, you can leave it in the buffer. Then, other data arrives, you just append it to the buffer:

    4 X X X X 3 X X X
            [---2---]
    

    You then have 2 complete messages that you can easily parse.

    If you do it, don't forget to send any length in a host-independant form (ntohs and ntohl can help).