Understanding TCP/IP is essential for building networked applications. Let's explore the fundamentals that power the internet and your applications.
The TCP/IP Stack
TCP/IP is organized into four layers:
- 1Application Layer: HTTP, FTP, SMTP
- 2Transport Layer: TCP, UDP
- 3Internet Layer: IP, ICMP
- 4Link Layer: Ethernet, Wi-Fi
TCP: Reliable Delivery
TCP provides reliable, ordered delivery of data.
Three-Way Handshake
Client → Server: SYN
Server → Client: SYN-ACK
Client → Server: ACKFlow Control
TCP uses sliding windows for flow control:
typescript
class TCPWindow {
private windowSize: number;
private received: Map<number, Buffer> = new Map();
private expectedSeq: number = 0;
constructor(windowSize: number) {
this.windowSize = windowSize;
}
receive(seq: number, data: Buffer): boolean {
if (seq < this.expectedSeq) {
return false; // Duplicate
}
if (seq >= this.expectedSeq + this.windowSize) {
return false; // Outside window
}
this.received.set(seq, data);
// Process in-order data
while (this.received.has(this.expectedSeq)) {
const data = this.received.get(this.expectedSeq)!;
this.processData(data);
this.received.delete(this.expectedSeq);
this.expectedSeq++;
}
return true;
}
private processData(data: Buffer) {
// Deliver to application
}
}UDP: Fast but Unreliable
UDP sacrifices reliability for speed:
typescript
import dgram from 'dgram';
const socket = dgram.createSocket('udp4');
socket.send(Buffer.from('Hello'), 8080, 'localhost');
socket.on('message', (msg, rinfo) => {
console.log(`Received ${msg} from ${rinfo.address}:${rinfo.port}`);
});HTTP and HTTPS
HTTP is the foundation of web communication.
HTTP/1.1
typescript
import http from 'http';
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World');
});
server.listen(3000);HTTP/2
HTTP/2 introduces multiplexing and header compression:
typescript
import http2 from 'http2';
const server = http2.createServer((req, res) => {
res.writeHead(200, { 'content-type': 'text/html' });
res.end('<h1>Hello HTTP/2</h1>');
});
server.listen(3000);Conclusion
TCP/IP fundamentals are crucial for building reliable networked applications. Understanding these protocols helps you debug issues and optimize performance.