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

Client Handler Class

A single ClientHandler looks after one connection from cradle to grave. It reads messages off the socket, mutates shared state, and pushes broadcasts back out.

Implementation

cpp
class ClientHandler {
int fd;
std::shared_ptr<SharedState> state;
std::string username;
LineReader reader;
public:
ClientHandler(int fd, std::shared_ptr<SharedState> state)
: fd(fd), state(state), reader(fd) {}
~ClientHandler() {
if (!username.empty()) {
state->remove_user(username);
state->broadcast(username + " left the chat.\n");
}
close(fd);
}
void run() {
// Wait for JOIN command
if (!handle_join()) return;
// Main message loop
while (true) {
std::string line = reader.read_line();
if (line.empty()) break;
Message msg = parse_message(line);
if (!dispatch(msg)) break;
}
}
private:
bool handle_join() {
std::string line = reader.read_line();
if (line.empty()) return false;
Message msg = parse_message(line);
if (msg.command != "JOIN" || msg.data.empty()) {
send_to_client("ERROR:Must JOIN first\n");
return false;
}
// Only claim the name once add_user succeeds. Setting username
// first would make our destructor remove the user who owns it.
if (!state->add_user(msg.data, fd)) {
send_to_client("ERROR:Username taken\n");
return false;
}
username = msg.data;
send_to_client("OK:Welcome, " + username + "!\n");
state->broadcast(username + " joined the chat.\n", username);
return true;
}
bool dispatch(const Message &msg) {
if (msg.command == "MSG") {
std::string formatted = "[" + username + "]: " + msg.data + "\n";
state->broadcast(formatted, username); // don't echo to the sender
return true;
}
if (msg.command == "LIST") {
auto users = state->list_users();
std::string list = "Online: ";
for (size_t i = 0; i < users.size(); i++) {
if (i > 0) list += ", ";
list += users[i];
}
send_to_client(list + "\n");
return true;
}
if (msg.command == "QUIT") {
return false;
}
send_to_client("ERROR:Unknown command\n");
return true;
}
void send_to_client(const std::string &data) {
size_t sent = 0;
while (sent < data.size()) { // send() may stop short
ssize_t n = send(fd, data.c_str() + sent, data.size() - sent, MSG_NOSIGNAL);
if (n < 0 && errno == EINTR) continue;
if (n <= 0) return; // peer gone: the read loop will notice and exit
sent += static_cast<size_t>(n);
}
}
};
Key Concept

All the cleanup lives in the destructor: pull the user out of shared state, tell everyone they left, close the socket. RAII means it fires whether the client said QUIT politely, dropped the TCP connection, or blew up an exception on the way out.

Every path through a handler's life ends in the same place, the destructor:

Error Handling

handle_join() and dispatch() return false whenever the client should be cut loose. The run() loop just listens for that signal. Flat control flow, no pyramids of if.

Testing with netcat

You can test the handler with netcat:

bash
# Terminal 1: start the server
./chat-server 8080
# Terminal 2: connect as alice
nc localhost 8080
JOIN:alice
MSG:Hello!
# Terminal 3: connect as bob
nc localhost 8080
JOIN:bob
MSG:Hi alice!
LIST:

Each terminal sees what the others type. Broadcasting working, end to end.