← All lessons
How TCP delivers data
The three-way handshake
Client
shop.test
client.js
import net from "node:net"; // connect() runs the whole handshake for youconst sock = net.connect(80, "shop.test");sock.on("connect", () => { sock.write("GET /");});tcp.js
// clientconst x = randomSeq();send({ flags: "SYN", seq: x }); // serverconst y = randomSeq();send({ flags: "SYN+ACK", seq: y, ack: x + 1 }); // client: both sides are ESTABLISHED nowsend({ flags: "ACK", seq: x + 1, ack: y + 1 }); // data counts bytes from x + 1send({ seq: x + 1, data: "GET /" });Lose a segment and TCP sends it again
Client
Network
Server
sender.js
const MSS = 4; // bytes per segment, tiny on purpose for (let off = 0; off < data.length; off += MSS) { const seq = next + off; send({ seq, data: data.slice(off, off + MSS) }); timer.start(seq);} on("ack", (ack) => { timer.clearBelow(ack); if (ack > lastAck) { lastAck = ack; dups = 0; } else if (++dups === 3) resend(ack);});on("timeout", (seq) => resend(seq));receiver.js
on("segment", (seg) => { buffer.set(seg.seq, seg.data); while (buffer.has(next)) { const data = buffer.take(next); app.push(data); next += data.length; } send({ ack: next }); // next byte I need});Out of order but read in order
On the network tap one to let it arrive
Receiver buffer
app reads
ACK
One late segment holds up every byte behind it
receiver.js
on("segment", (seg) => { buffer.set(seg.seq, seg.data); while (buffer.has(next)) { const data = buffer.take(next); app.push(data); next += data.length; } send({ ack: next }); // next byte I need});Topics
Next: How HTTP caching works
Open lesson