Nathan
Nathan

Reputation: 672

Merging data in 2 or more TCP/IP Packets

I am supposed to get some XML data from the server say,

     <?xml><a></a><?xml><a></a><?xml><a></a><?xml><a></a>

Suppose the packets are received in the following order

     <?xml><a>
     </a><?xml><a></a><?xml>
     <a></a>

How can I formulate the logic to parse this kind of data?

Upvotes: 0

Views: 650

Answers (1)

Adam Liss
Adam Liss

Reputation: 48290

The short answer is that you don't need to worry about the order; TCP handles reassembly for you.

TCP is a streaming protocol, and each packet contains a sequence number that allows the network stack to reassemble incoming packets in the right order. It will also automatically re-send any packets that get dropped or corrupted during transmission. However, unlike UDP, which transmits a complete message at a time, TCP just keeps sending data until the connection closes, with no protocol-level concept of individual messages.

I think your question isn't about ordering, but about knowing when you've received all of the data. There are generally two ways to go about that.

First, the server can close the connection when it's finished sending the data. The client makes a request, accumulates the response until the connection is closed, and then passes all of the data it received onward to the application.

Second, an application can frame the data itself, either by marking the end of each message or by inserting a byte count at the beginning of each message. The receiver waits for the specified number of bytes to arrive and passes them on to the application.

There's actually a third method, but it's error-prone and generally considered poor practice: the client can simply wait until it stops receiving data for some length of time, assuming the timeout indicates the end of a message. But this can cause unnecessary delays while the client waits for the timeout, and it can also indicate the end of a message prematurely if there are large delays in the network. You should consider it a fail-safe that prevents the client from hanging if the server "goes away" in the middle of a message, or you can use it as a last resort if none of the other methods will work. But there's a good chance it will fail intermittently, so don't tell anyone you heard it from me. :-)

Good luck!

Upvotes: 2

Related Questions