Protocol Design
A protocol is the contract between client and server. We're going to design a small text-based one for the chat-server capstone.
Message Format
Our chat protocol uses newline-delimited messages with a command prefix:
CMD:DATA\nExamples:
JOIN:alice\n- user "alice" joins the chatMSG:Hello everyone!\n- send a messageQUIT:\n- disconnectLIST:\n- request list of online users
Message Parser
struct Message { std::string command; std::string data;};
Message parse_message(const std::string &raw) { auto pos = raw.find(':'); if (pos == std::string::npos) { return {"UNKNOWN", raw}; } return {raw.substr(0, pos), raw.substr(pos + 1)};}Line-Based Reading
Since our messages are newline-delimited, we need to read until we see \n:
class LineReader { int fd; std::string buffer;public: LineReader(int fd) : fd(fd) {}
std::string read_line() { while (true) { auto pos = buffer.find('\n'); if (pos != std::string::npos) { std::string line = buffer.substr(0, pos); buffer = buffer.substr(pos + 1); return line; }
char chunk[1024]; int n = recv(fd, chunk, sizeof(chunk), 0); if (n <= 0) return ""; buffer.append(chunk, n); } }};Network data arrives in chunks of whatever size the kernel feels like handing you. One recv() might return half a message. The next, two and a bit. The LineReader buffers what comes in and slices on newlines, so the rest of your code only ever sees whole messages. This framing problem shows up in every protocol you'll ever design.
Here's the same reader with recv() swapped for a fake socket that delivers bytes in awkward chunks: one message split across two reads, two messages arriving in one. Before you run it, predict how many messages get printed. Pay attention to what follows there?.
Two more gaps worth closing in the real reader: telnet and many other clients end lines with \r\n, so strip a trailing \r, and a peer that never sends a newline will grow buffer without limit, so cap it (4 KB is plenty for chat) and drop the connection when it's exceeded.
Message Serialisation
std::string format_message(const std::string &cmd, const std::string &data) { return cmd + ":" + data + "\n";}
struct Client { int fd; std::string name; };std::mutex clients_mutex; // guards connected_clientsstd::vector<Client> connected_clients; // every handler thread touches this
// Server broadcasting a message to all clientsvoid broadcast(const std::string &sender, const std::string &text) { std::string msg = format_message("MSG", "[" + sender + "] " + text); std::lock_guard<std::mutex> lock(clients_mutex); for (auto &client : connected_clients) { send(client.fd, msg.c_str(), msg.size(), 0); }}Protocol State Machine
A chat session follows a state machine. This one is drawn from what handle_client below actually does, including the inputs it quietly ignores:
The self-loops are the negative cases. A MSG sent before JOIN vanishes without a reply, and so does a QUIT, so a client that never joins can only leave by closing the connection. The capstone's handler answers a pre-JOIN command with an ERROR: reply and hangs up instead.
Handling this in code:
enum class ClientState { CONNECTED, ACTIVE, DISCONNECTED };
void handle_client(int fd) { ClientState state = ClientState::CONNECTED; LineReader reader(fd);
while (state != ClientState::DISCONNECTED) { std::string line = reader.read_line(); if (line.empty()) break;
Message msg = parse_message(line);
switch (state) { case ClientState::CONNECTED: if (msg.command == "JOIN") { state = ClientState::ACTIVE; } break; case ClientState::ACTIVE: if (msg.command == "MSG") { /* broadcast */ } else if (msg.command == "QUIT") { state = ClientState::DISCONNECTED; } break; default: break; } }}An explicit state machine makes the protocol much easier to reason about. Adding new commands later is mostly a question of adding cases.
Challenges
Parse a simple protocol message in the format 'CMD:DATA' and print the command and data separately.