Overview
TCP (Transmission Control Protocol) and UDP (User Datagram Protocol) are the two primary transport layer protocols used for sending data across a network. They offer different trade-offs between reliability and speed.
Core Concepts
- TCP (Transmission Control Protocol):
- Connection-Oriented: Requires a “handshake” to establish a connection before data is sent.
- Reliable: Guarantees that data arrives in order and without errors. It uses acknowledgments (ACKs) and retransmissions for lost packets.
- Flow Control: Manages the speed of data transmission to prevent the receiver from being overwhelmed.
- Congestion Control: Slows down transmission when the network is congested.
- UDP (User Datagram Protocol):
- Connectionless: Data is sent without establishing a connection.
- Unreliable: Does not guarantee delivery, order, or integrity. It’s a “fire and forget” protocol.
- Fast: Lower overhead because it lacks handshakes, ACKs, and retransmissions.
Code Examples
// Conceptual TCP socket (Node.js)
import net from 'net';
const server = net.createServer((socket) => {
socket.write('Hello TCP Client!');
socket.on('data', (data) => console.log('Received:', data.toString()));
});
server.listen(8080);
// Conceptual UDP socket (Node.js)
import dgram from 'dgram';
const server = dgram.createSocket('udp4');
server.on('message', (msg, rinfo) => {
console.log(`Received ${msg} from ${rinfo.address}:${rinfo.port}`);
});
server.bind(41234);
Use Cases
- TCP: Web browsing (HTTP), Email (SMTP), File transfer (FTP), SSH.
- UDP: Video streaming, VoIP, Online gaming, DNS.
Gotchas
- Head-of-Line Blocking: In TCP, if one packet is lost, all subsequent packets must wait for its retransmission, even if they arrived successfully.
- UDP Packet Loss: Application developers must handle packet loss or out-of-order delivery themselves if they use UDP.
