TCP vs UDP
The two main protocols of the Transport layer: TCP and UDP.
01Basic Differences
| Feature | TCP | UDP |
|---|---|---|
| Connection | Connection-based | Connectionless |
| Reliability | 100% guaranteed | No guarantee |
| Ordering | Ordered delivery | Unordered |
| Speed | Slow | Fast |
| Overhead | High | Low |
02TCP - Like a Phone Call
TCP = Reliable
Features:
- 3-Way Handshake: Connection setup
- Sequence Numbers: Ordering guarantee
- Acknowledgments: Each packet confirmed
- Retransmission: Lost packets resent
- Flow Control: Speed control
TCP Connection Setup:
code
Client Server
|--- SYN --->|
|<-- SYN+ACK-|
|--- ACK --->|
[Connection OK]
TCP Data Transmission:
code
Data 1 →→→ ACK 1
Data 2 →→→ ACK 2
Data 3 →→→ LOST!
Data 3 →→→ ACK 3 (Resend)
03UDP - Like a Letter
UDP = Best Effort
Features:
- Connectionless: No handshake
- Fast: Low overhead
- Simple: Just send
- May be lost: No guarantee
UDP Transmission:
code
Data 1 →→→ ✓
Data 2 →→→ ✓
Data 3 →→→ ✗ (Lost, no retry)
Data 4 →→→ ✓
04When to Use Which?
Use TCP:
- 🌐 Websites (HTTP/HTTPS)
- 📧 Email (SMTP, IMAP)
- 📁 File transfer (FTP)
- 🔐 SSH connections
Use UDP:
- 🎮 Online games
- 📹 Video streaming
- 📞 VoIP (Voice calls)
- 🔍 DNS queries
- 📡 DHCP
05Game Example
In online gaming:
- Character position: UDP (speed matters, loss is OK)
- Purchase transaction: TCP (must arrive)
06Summary
- TCP = Reliable but slow (web, email)
- UDP = Fast but unreliable (games, video)
- Choose the right protocol for your needs!