On Github mattgodbolt / seasocks-slides
int main() { auto logger = make_shared<PrintfLogger>(Logger::DEBUG); Server server(logger); server.serve("web", 9000); }
int main() { auto logger = make_shared<PrintfLogger>(Logger::DEBUG); Server server(logger); server.addWebSocketHandler("/chat", make_shared<Handler>()); server.serve("web", 9000); }
struct Handler : WebSocket::Handler { unordered_set<WebSocket *> _cons; void onConnect(WebSocket *con) override { _cons.emplace(con); send(con->credentials()->username + " has joined"); } void onDisconnect(WebSocket *con) override { _cons.erase(con); send(con->credentials()->username + " has left"); } void onData(WebSocket *con, const char *data) override { send(con->credentials()->username + ": " + data); } void send(string msg) { for (auto *con : _cons) con->send(msg); } };
std::thread tick([&]{ for (;;) { sleep(1); myHandler->tick(); } }); tick.detach();
void MyHandler::tick() { // anything interesting has to happen on the server // thread. It's pretty easy to run work there: server().execute([this]{ send("Tick!"); }); }