In this lesson, you will learn how the TCP three-way handshake establishes a reliable, ordered connection before any Node.js data streams begin to flow.
The Foundation of Reliable Connections
In Node.js, when you use the net module to create a server or a client, you are relying on the Transmission Control Protocol (TCP). Before your data streams can be piped or processed, TCP must ensure that both sides of the conversation are ready. Because the internet is a "best-effort" medium where packets can be lost, delayed, or reordered, we cannot simply start sending data. Instead, we use the three-way handshake.
The Three-Way Handshake
Think of the handshake as a formal introduction between a Client and a Server:
- SYN (Synchronize): The client sends a packet to the server with a "Sequence Number" to start the conversation. It’s essentially saying, "I’d like to talk, and my messages will start with this index."
- SYN-ACK (Synchronize-Acknowledge): The server receives the request and sends back a response. It acknowledges the client’s number and provides its own initial Sequence Number. It’s saying, "I hear you, I'm ready, and here is how I will number my messages."
- ACK (Acknowledge): The client sends one final acknowledgment to the server. It says, "Got it, I’m ready for your data."
Once this handshake is complete, the state of the socket changes to connected.
Why It Matters for Streams
Node.js streams are abstractions that rely on this underlying reliable pipe. Because the handshake establishes sequence numbers, TCP can track exactly which bytes have been sent and received. If a segment of your stream is lost during transmission, TCP notices a gap in the sequence numbers and automatically requests a retransmission.
const net = require('net');
const client = net.connect({ port: 8080 }, () => {
// This callback only fires after the 3-way handshake is complete.
console.log('Handshake successful, stream can now start.');
});
Because of this protocol, when your Node.js application writes to a stream, you can be confident that the data will arrive intact and in the correct order, regardless of the underlying network chaos.
Key Takeaway: The three-way handshake creates a synchronized, reliable sequence of bytes, allowing Node.js to treat unstable network connections as stable, readable, and writable data streams.