WebSockets
WebSockets give you bidirectional, low-latency channels on the same port as your HTTP routes. Garvan exposes Crow's WebSocket API unchanged.
Defining a websocket route
CROW_WEBSOCKET_ROUTE(app, "/ws")
.onopen([&](crow::websocket::connection &conn) {
CROW_LOG_INFO << "client connected: " << &conn;
})
.onmessage([&](crow::websocket::connection &conn,
const std::string &data, bool is_binary) {
conn.send_text("you said: " + data);
})
.onclose([&](crow::websocket::connection &conn, const std::string &reason, uint16_t code) {
CROW_LOG_INFO << "client gone: " << reason;
});
Connection events
You'll typically want three handlers: onopen to track new connections, onmessage for incoming frames, and onclose to clean up state. Store connections in a thread-safe container if you need to broadcast.
std::mutex mu;
std::unordered_set<crow::websocket::connection*> clients;