Building a TCP Echo Server
Walk through a complete TCP echo server implementation.
Building a TCP Echo Server is a free C++ Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C++ Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Goal
Build a minimal TCP server that accepts a connection, reads bytes, and writes them back. The "Hello World" of network programming.
Server Skeleton
The server flow: create socket, bind, listen, accept, handle. Loop forever.
int srv = socket(AF_INET, SOCK_STREAM, 0);
bind(srv, (sockaddr*)&addr, sizeof(addr));
listen(srv, 10);
while (true) {
int client = accept(srv, nullptr, nullptr);
handle(client);
close(client);
}Reuse Address Option
Set SO_REUSEADDR so the server can restart immediately without waiting for the OS to release the port.
int yes = 1;
setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));The Echo Loop
Read into a buffer; write the same bytes back. Stop when the client closes the connection.
void handle(int client) {
char buf[1024];
while (true) {
ssize_t n = recv(client, buf, sizeof(buf), 0);
if (n <= 0) break; // closed or error
send(client, buf, n, 0);
}
}Partial Reads and Writes
Both recv and send can transfer fewer bytes than requested. For a stream-based protocol, loop until done.
ssize_t total = 0;
while (total < n) {
ssize_t s = send(client, buf + total, n - total, 0);
if (s <= 0) break;
total += s;
}Handling Multiple Clients
The simplest approach: a new thread per connection. Works for hundreds of clients; struggles at thousands.
while (true) {
int client = accept(srv, nullptr, nullptr);
std::thread([client]{ handle(client); close(client); }).detach();
}Better: Thread Pool
Spawning a thread per connection wastes resources at scale. A fixed thread pool with a work queue scales better.
Graceful Shutdown
Handle SIGTERM/SIGINT to close the listening socket cleanly. RAII helps ensure all client sockets are closed too.
Error Handling
Treat errors as expected: clients disconnect, networks hiccup, OS limits run out. Log and continue — do not crash on a bad client.
Logging Each Client
Log the remote address for observability.
sockaddr_in remote{};
socklen_t len = sizeof(remote);
int client = accept(srv, (sockaddr*)&remote, &len);
char ip[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &remote.sin_addr, ip, sizeof(ip));
std::cout << "client " << ip << ":" << ntohs(remote.sin_port);Testing with netcat
Test your echo server interactively with nc.
nc 127.0.0.1 8080
hello
hello # echoed backBeyond Echo
From echo you can extend to:
- Line-based protocols (HTTP-like)
- Framed binary protocols (length-prefix)
- JSON or Protobuf messages
Quick Check
What is the purpose of the SO_REUSEADDR socket option?
Recap
A minimal TCP echo server: socket, setsockopt SO_REUSEADDR, bind, listen, accept-in-loop. For multiple clients, spawn threads or use a thread pool. For high scale, switch to async I/O (next lesson).
Frequently asked questions
Is the “Building a TCP Echo Server” lesson free?
Yes — the full text of “Building a TCP Echo Server” is free to read here on the web, and the C++ Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C++ Academy course, upgrade to CoddyKit PRO.
What will I learn in “Building a TCP Echo Server”?
Walk through a complete TCP echo server implementation. You practise C++ Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start C++ Academy?
No prior experience is required. C++ Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Building a TCP Echo Server” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this C++ Academy lesson?
Yes. Every C++ Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- BSD Sockets API in C++
- Building a TCP Echo Server
- Asynchronous IO with epoll and kqueue
- Using Boost Asio for Modern Async IO