Skip to main content
Be Bitwise
C++Capstone: Chat Server

The Complete Server

Time to wire all the pieces together.

main.cpp

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.

Try itAdd your own arguments to the inputs array, then swap parse_port into main.cpp so a bad argument prints a usage message instead of binding somewhere unexpected.
C++ (GCC 9.2.0)

Compilation

bash
g++ -std=c++17 -pthread main.cpp server.cpp shared_state.cpp -o chat-server
./chat-server 8080

Forget -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:

bash
# Terminal 1: Start server
./chat-server 8080
# Terminal 2: Alice
nc localhost 8080
JOIN:alice
MSG:Hello everyone!
# Terminal 3: Bob
nc localhost 8080
JOIN:bob
MSG: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.

Try itDelete the std::signal line and run it again: the process dies on SIGPIPE before it can print that the server is still running.
C++ (GCC 9.2.0)
Key Concept

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:

  1. Private messages - add a WHISPER:user:message command
  2. Chat rooms - let users create and join rooms
  3. Persistent history - save messages to a file
  4. User authentication - require a password on JOIN
  5. GUI client - build a client with a graphical interface
  6. 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; poll with 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'.

C++ (GCC 9.2.0)