Dunes Buggy
Dunes Buggy

Reputation: 1819

How does TCP implement/guarantee in-order data transmission?

I was wondering how exactly does TCP implement in-order delivery.

lets say this is list of events

  1. packet1 sent , ack received.
  2. packet2 sent , ack not-received.
  3. packet3 sent.
  4. packet4 sent.
  5. ack4 received.
  6. ack3 received.
  7. ack2 received.

Can you describe to me what exactly happens sequentially?

Upvotes: 13

Views: 7442

Answers (2)

George Skoptsov
George Skoptsov

Reputation: 3961

The short answer is that each packet contains offset information (disguised as sequence number), specifying where in the stream its payload lies.

Let's say the following occurred: packet 1 is received, packet 2 is not received, and packet 3 and 4 are received. At this point receiving TCP stack knows where to copy contents of packets 3 and 4 on the buffer, and it knows that it still hasn't received prior data, so it will make packet 1 data available for reading, but it won't make packet 3 or 4 data available until packet 2 is received.

Transmitting TCP stack generally does not wait for acknowledgements for any single packet before sending out the next one, but if it does not receive an acknowledgement for a given packet (and ACKs can and are bundled together in a single packet for efficiency), it will retransmit it until an ACK is received.

Exact sequence of events depends on network conditions, TCP stack implementation, chosen TCP policy, socket options and other factors.

Upvotes: 13

paxdiablo
paxdiablo

Reputation: 881463

TCP packets have sequence numbers (byte offsets since the start, from memory) and the ACK messages acknowledge that a specific offset has been received:

enter image description here

So you could end up with a situation like:

data 1 (10 bytes)          ->
                           <- ack (10, data1)
data 2 (15 bytes)          ->
data 3 (10 bytes)          ->
data 4 ( 8 bytes)          ->
                           <- ack (25, data1/2/3)
                           <- ack (33, data1/2/3/4)

In other words, the sender can continue to send regardless of acknowledgments up to the point where its buffers are full (it has to keep unacknowledged packets in case it needs to re-transmit them).

This "disconnect" between sends and acknowledgments can greatly speed up the data flow.

At the receiving end, the packets can arrive out of order, and they're kept until something can be delivered to the higher levels in order.

For example, if data 3 arrived before data 2, the receiving end would hold on to it until data 2 arrived, then both of them would be sent upwards for delivery.

Upvotes: 7

Related Questions