This repository is designed to teach the fundamentals of networking and socket programming using Go.
- How the Internet Works
- What is TCP/IP
- TCP vs UDP
- TCP Server Implementation
- TCP Client Implementation
- Real-World Example: Chat Server
- Running the Examples
The Internet is a global network of interconnected computers that communicate using standardized protocols.
-
Client-Server Model:
- Client: Initiates requests (e.g., web browser, mobile app)
- Server: Responds to requests (e.g., web server, database server)
-
Network Layers (OSI Model):
- Application Layer: HTTP, FTP, SMTP, etc.
- Transport Layer: TCP, UDP
- Network Layer: IP (Internet Protocol)
- Data Link Layer: Ethernet, WiFi
- Physical Layer: Cables, wireless signals
-
Data Flow:
Application (Browser) → TCP → IP → Network Interface → Physical Medium ↓ Internet (Routers) ↓ Physical Medium → Network Interface → IP → TCP → Application (Server) -
IP Addresses: Unique identifiers for devices (e.g., 192.168.1.1, 2001:db8::1)
-
Ports: Endpoints for communication (e.g., HTTP uses port 80, HTTPS uses port 443)
TCP/IP (Transmission Control Protocol/Internet Protocol) is the fundamental protocol suite that powers the Internet.
- Purpose: Routes packets from source to destination
- Addressing: Uses IP addresses to identify devices
- Connectionless: Each packet is independent
- Unreliable: No guarantee of delivery
- Purpose: Ensures reliable, ordered delivery of data
- Connection-oriented: Establishes a connection before data transfer
- Features:
- Reliability: Guarantees data delivery
- Ordering: Data arrives in the correct sequence
- Error Checking: Detects and corrects errors
- Flow Control: Prevents overwhelming the receiver
- Congestion Control: Adapts to network conditions
Client Server
| |
|--------- SYN ---------->| (Client initiates connection)
| |
|<------ SYN-ACK ---------| (Server acknowledges)
| |
|--------- ACK ---------->| (Client confirms)
| |
| Connection Established |
| Feature | TCP | UDP |
|---|---|---|
| Connection | Connection-oriented | Connectionless |
| Reliability | Guaranteed delivery | No guarantee |
| Ordering | Maintains order | No ordering |
| Speed | Slower (due to overhead) | Faster |
| Header Size | 20 bytes | 8 bytes |
| Error Checking | Extensive | Basic checksum |
| Flow Control | Yes | No |
| Use Cases | Web browsing, email, file transfer | Video streaming, online gaming, DNS |
- ✅ Data integrity is critical
- ✅ Order matters
- ✅ Connection state is needed
- Examples: HTTP, HTTPS, FTP, SSH, email
- ✅ Speed is more important than reliability
- ✅ Some data loss is acceptable
- ✅ Real-time communication
- Examples: Video streaming, VoIP, online gaming, DNS
This repository demonstrates a TCP server that:
- Listens for incoming connections
- Handles multiple clients concurrently
- Receives structured messages (JSON)
- Processes requests and sends responses
-
Server Structure (
server/server.go):- Server configuration
- Connection management
- Message handling
-
Protocol (
protocol/protocol.go):- Structured message format
- Request/Response types
- JSON encoding/decoding
-
Concurrent Handling:
- Each client runs in a separate goroutine
- Non-blocking I/O
- Graceful connection cleanup
// Create and start server
srv := server.NewServer(":8080")
srv.Start()The TCP client demonstrates:
- Establishing TCP connections
- Sending structured messages
- Receiving and parsing responses
- Connection lifecycle management
-
Client Structure (
client/client.go):- Connection management
- Message sending/receiving
- Error handling
-
Protocol Compliance:
- Same message format as server
- JSON serialization
- Type-safe communication
// Create client and connect
client := client.NewClient("localhost:8080")
client.Connect()
// Send message
response := client.SendMessage("ECHO", "Hello, Server!")This repository includes a complete chat server implementation demonstrating:
- Multi-client support: Multiple users can connect simultaneously
- Message broadcasting: Messages sent to all connected clients
- User management: Username registration and tracking
- Message history: Server stores recent messages
- Command system:
REGISTER: Set usernameMESSAGE: Send chat messageLIST_USERS: Get list of online usersLIST_MESSAGES: Get recent message historyECHO: Simple echo testTIME: Get server time
Server (Port 8080)
├── Client 1 (Goroutine)
├── Client 2 (Goroutine)
├── Client 3 (Goroutine)
└── Message Broker (Broadcasts messages)
# Ensure Go is installed
go version
# Should output: go version go1.21 or higher# Run server from cmd/server
go run cmd/server/main.go
# Or build and run
go build -o server cmd/server/main.go
./serverOption A: Interactive Client
go run cmd/client/main.goOption B: Multiple Clients Open multiple terminals and run the client in each:
# Terminal 1
go run cmd/client/main.go
# Terminal 2
go run cmd/client/main.go
# Terminal 3
go run cmd/client/main.goClient 1:
Connected to server at localhost:8080
Enter command (REGISTER/MESSAGE/LIST_USERS/ECHO/TIME/QUIT): REGISTER
Enter data: Alice
Response: Registration successful. Welcome, Alice!
Enter command: MESSAGE
Enter data: Hello everyone!
Response: Message broadcasted
Client 2:
Connected to server at localhost:8080
Enter command: REGISTER
Enter data: Bob
Response: Registration successful. Welcome, Bob!
[Broadcast] Alice: Hello everyone!
Enter command: LIST_USERS
Response: Online users: Alice, Bob
Enter command: LIST_MESSAGES
Response: Recent messages:
[10:30:15] Alice: Hello everyone!
tcp/
├── README.md # This file
├── CONCEPTS.md # Detailed networking concepts
├── go.mod # Go module definition
├── main.go # Quick demo
├── protocol/
│ └── protocol.go # Message protocol definition
├── server/
│ └── server.go # TCP server implementation
├── client/
│ └── client.go # TCP client implementation
└── cmd/
├── server/
│ └── main.go # Server entry point
└── client/
└── main.go # Client entry point
- Start with concepts: Read this README and CONCEPTS.md
- Examine protocol: Understand the message format in
protocol/protocol.go - Study server: Review
server/server.gofor server implementation - Study client: Review
client/client.gofor client implementation - Run examples: Start server and clients to see it in action
- Experiment: Modify code, add features, break things and fix them!
- Add authentication: Require password for user registration
- Private messages: Implement direct messaging between users
- Room system: Add chat rooms/channels
- File transfer: Implement file sending capability
- Encryption: Add TLS for secure communication
- Protocol buffer: Replace JSON with Protocol Buffers
- UDP comparison: Implement same chat using UDP
- CONCEPTS.md - Deep dive into networking concepts with detailed TCP/IP explanations
- SEQUENCE_NUMBERS.md - Quick reference guide for TCP sequence numbers
- SEQUENCE_NUMBERS_VISUAL.md - Visual diagrams and examples of sequence numbers
- LIST_MESSAGES.md - Documentation for the message history feature
- EXERCISES.md - Practice exercises and challenges
- REAL_WORLD_EXAMPLES.md - Real-world socket programming applications
- QUICKSTART.md - Get started in 5 minutes
This repository is for educational purposes. Feel free to use, modify, and share.
This is an educational project. Feel free to:
- Report issues
- Suggest improvements
- Add more examples
- Improve documentation
Happy Learning! 🎉