Sikau

Computer networks · Day 7 · about 35 min

Sequence numbers

Put out-of-order, duplicated and overlapping segments back together.

Packets arrive in any order

Packets can take different paths, so they arrive late, twice or out of order. TCP numbers every byte with a sequence number; the receiver delivers bytes only in order and ACKs the next byte it's still waiting for — which tells the sender what to resend.

Reassembly

function reassemble(segments) {
  const sorted = [...segments].sort((a, b) => a.seq - b.seq);
  let next = 0; // the next byte we're waiting for
  let data = "";
  for (const s of sorted) {
    if (s.seq + s.data.length <= next) continue; // all old: a duplicate
    if (s.seq > next) break;                     // a gap: wait for the missing bytes
    data += s.data.slice(next - s.seq);          // keep only the new part of an overlap
    next = s.seq + s.data.length;
  }
  return { data, ack: next };
}

The rest of this lesson

  • Trimming overlapsexplain
  • ACKs drive retransmissionexplain
  • What's acknowledged?predict
  • What can be delivered?predict
  • Reassemblewrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 12 lessons of Computer networks