The Complete Server
Time to wire all the pieces together.
main.cpp
#include <csignal>#include <iostream>#include "server.h"
int main(int argc, char *argv[]) { std::signal(SIGPIPE, SIG_IGN); // a vanished client must not kill the server (see below) uint16_t port = 8080; if (argc > 1) port = std::stoi(argv[1]);
try { ChatServer server; server.start(port); } catch (const std::exception &e) { std::cerr << "Fatal: " << e.what() << std::endl; return 1; } return 0;}That std::stoi line trusts its input more than it should: stoi stops at the first non-digit, and the int it returns is silently squeezed into 16 bits. Predict what port ./chat-server 70000 would listen on, then compare it with a stricter parser.
Compilation
g++ -std=c++17 -pthread main.cpp server.cpp shared_state.cpp -o chat-server./chat-server 8080Forget -pthread and the link step will scream at you about missing symbols for std::thread and std::mutex.
Testing the Complete Server
Open three terminals:
# Terminal 1: Start server./chat-server 8080
# Terminal 2: Alicenc localhost 8080JOIN:aliceMSG:Hello everyone!
# Terminal 3: Bobnc localhost 8080JOIN:bobMSG:Hi Alice!LIST:QUIT:One thing those terminals won't show you unless you're unlucky: what happens when a client vanishes. Once a peer has gone, writes to its socket soon start failing with EPIPE (with TCP, the first write after the close can still appear to succeed), and the kernel also sends the writer SIGPIPE, whose default action kills the process, taking every other client with it. The broadcast and send_to_client both pass MSG_NOSIGNAL, but that flag is Linux-only and any send() or write() you add later could forget it, so main also ignores SIGPIPE once at the top as a backstop.
The capstone leans on pretty much every C++ idea you've met. RAII drives socket and lock cleanup. OOP keeps each responsibility in its own class. shared_ptr handles the shared ownership of SharedState. STL containers (unordered_map, vector, deque) hold the data; templates are what made them possible. Move semantics quietly fire whenever you spin a thread. None of it is decoration. Take any one piece out and the build falls over.
What You Have Built
Your chat server now handles:
- Many concurrent clients via threads
- A text-based protocol with parsing and routing
- Thread-safe shared state behind a mutex
- Tidy resource teardown through RAII
- Disconnects and bad input without falling over
The scale differs, but the bones are the same as what powers real messaging platforms and game servers.
Extension Ideas
A few directions if you want to keep going:
- Private messages - add a
WHISPER:user:messagecommand - Chat rooms - let users create and join rooms
- Persistent history - save messages to a file
- User authentication - require a password on JOIN
- GUI client - build a client with a graphical interface
- Graceful shutdown - the accept loop never exits, so Ctrl+C just kills the process. Catch SIGINT with a flag, wake the blocked
accept(on Linux,shutdown()on the listening socket does it;pollwith a self-pipe works everywhere), and tell every client goodbye
Each extension stretches a different muscle. Because the architecture is modular, slotting one in rarely means tearing up what's already there.
Challenges
Create a ChatMessage class with a format() method that returns '[username]: message'.