Message Routing
SharedState is the spine of the chat server. It owns the user directory and ferries broadcasts out to whoever is connected.
Thread-Safe User Management
class SharedState { mutable std::mutex mtx; std::unordered_map<std::string, int> users;
public: bool add_user(const std::string &name, int fd) { std::lock_guard<std::mutex> lock(mtx); if (users.count(name)) return false; // username taken users[name] = fd; return true; }
void remove_user(const std::string &name) { std::lock_guard<std::mutex> lock(mtx); users.erase(name); }
std::vector<std::string> list_users() const { std::lock_guard<std::mutex> lock(mtx); std::vector<std::string> result; result.reserve(users.size()); for (const auto &[name, fd] : users) { result.push_back(name); } return result; }};Broadcasting
The broadcast method sends a message to all connected users:
void broadcast(const std::string &message, const std::string &exclude = "") { std::lock_guard<std::mutex> lock(mtx); for (const auto &[name, fd] : users) { if (name != exclude) { // send() is thread-safe for different fds ::send(fd, message.c_str(), message.size(), MSG_NOSIGNAL); } }}MSG_NOSIGNAL stops a write to a dead connection from raising SIGPIPE, whose default action kills the whole server. It's Linux-only: on macOS and the BSDs, set the SO_NOSIGPIPE socket option on each client socket instead (setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &one, sizeof one)), or ignore SIGPIPE process-wide with signal(SIGPIPE, SIG_IGN).
This version holds the mutex for every send(). Blocking sockets make that a real cost: one client that stops reading fills its socket buffer, its send() blocks, and every join, leave and broadcast waits behind it. Copying the fds out and sending after unlocking looks like the fix, but a handler could close its fd in between and a new client could be handed the same number. The proper answer is a per-client outbound queue that a writer thread drains; for this capstone, the simple lock is the honest trade.
The exclude parameter is how the sender opts out of receiving their own message. Alice doesn't need her words echoed back, and every chat server in existence has this knob.
Handling Disconnects During Broadcast
What if a client vanishes mid-broadcast? send() returns -1 with EPIPE. Worth handling cleanly:
void broadcast(const std::string &message, const std::string &exclude = "") { std::lock_guard<std::mutex> lock(mtx);
for (const auto &[name, fd] : users) { if (name == exclude) continue; ssize_t result = ::send(fd, message.c_str(), message.size(), MSG_NOSIGNAL); if (result < 0) { // Wake the dead client's handler: its recv() returns 0, and its // destructor removes the user and closes the fd ::shutdown(fd, SHUT_RDWR); } }}Erasing the user here would be tempting, but the handler thread would never find out: its socket would stay open, and its destructor would later call remove_user on a name that might by then belong to someone new. Shutting the socket down leaves the cleanup to the one place that owns it.
Message History
Bolting on a small message history gives newcomers some context:
class SharedState { // ... existing members ... std::deque<std::string> history; static constexpr size_t MAX_HISTORY = 50;
public: void add_to_history(const std::string &msg) { std::lock_guard<std::mutex> lock(mtx); history.push_back(msg); while (history.size() > MAX_HISTORY) { history.pop_front(); } }
std::vector<std::string> get_history() const { std::lock_guard<std::mutex> lock(mtx); return {history.begin(), history.end()}; }};Wire it into the handler from the previous lesson: call state->add_to_history(formatted) next to the broadcast in dispatch(), and after the welcome in handle_join() replay what's stored:
for (const auto &line : state->get_history()) { send_to_client(line);}A fresh user then drops straight into the conversation.
Performance Considerations
For a handful of clients the plain mutex holds up fine. Push it harder and the contention bites; at that point you might reach for:
- A reader-writer lock (
std::shared_mutex) when reads dominate - Lock-free queues for the message stream
- A dedicated broadcast thread to keep handler threads cheap
For learning, though, the single mutex is correct, obvious, and good enough.