Project 2: TCP Echo Server & Client (Blocking Sockets)

A server that listens on a port and echoes back whatever clients send, plus a client that connects, sends messages, and displays responses. The server handles one client at a time (blocking).

Quick Reference

Attribute Value
Primary Language C++
Alternative Languages C, Rust, Go
Difficulty Level 1: Beginner
Time Estimate Weekend
Knowledge Area TCP Sockets, Client-Server Model
Tooling Network debugging tool
Prerequisites Project 1, understanding of file descriptors

What You Will Build

A server that listens on a port and echoes back whatever clients send, plus a client that connects, sends messages, and displays responses. The server handles one client at a time (blocking).

Why It Matters

This project builds core skills that appear repeatedly in real-world systems and tooling.

Core Challenges

  • Setting up the server socket correctly → maps to bind(), listen(), accept() sequence
  • Handling partial reads/writes → maps to TCP is a byte stream, not message-oriented
  • Detecting client disconnection → maps to read() returning 0, handling SIGPIPE
  • Proper resource cleanup → maps to close() and RAII patterns

Key Concepts

  • TCP Socket Lifecycle: “UNIX Network Programming, Volume 1” Chapter 4 - Stevens
  • The listen() Backlog: “The Linux Programming Interface” Section 56.6.1 - Kerrisk
  • Partial I/O: “UNIX Network Programming, Volume 1” Section 3.9 - Stevens
  • RAII for Sockets: “Effective C++” Item 13 - Scott Meyers

Real-World Outcome

# Terminal 1: Start server
$ ./echo_server 9000
Echo server listening on port 9000...
Client connected from 127.0.0.1:52431
Received: "Hello, server!"
Sent: "Hello, server!"
Received: "Testing 123"
Sent: "Testing 123"
Client disconnected.

# Terminal 2: Run client
$ ./echo_client localhost 9000
Connected to localhost:9000
> Hello, server!
Server: Hello, server!
> Testing 123
Server: Testing 123
> ^C
Disconnected.

# Also works with netcat/telnet:
$ echo "Hello from nc" | nc localhost 9000
Hello from nc

Implementation Guide

  1. Reproduce the simplest happy-path scenario.
  2. Build the smallest working version of the core feature.
  3. Add input validation and error handling.
  4. Add instrumentation/logging to confirm behavior.
  5. Refactor into clean modules with tests.

Milestones

  • Milestone 1: Minimal working program that runs end-to-end.
  • Milestone 2: Correct outputs for typical inputs.
  • Milestone 3: Robust handling of edge cases.
  • Milestone 4: Clean structure and documented usage.

Validation Checklist

  • Output matches the real-world outcome example
  • Handles invalid inputs safely
  • Provides clear errors and exit codes
  • Repeatable results across runs

References

  • Main guide: LEARN_CPP_NETWORK_PROGRAMMING.md
  • “UNIX Network Programming, Volume 1” by W. Richard Stevens