example_ws.cpp 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. #include "crow.h"
  2. #include <unordered_set>
  3. #include <mutex>
  4. int main()
  5. {
  6. crow::SimpleApp app;
  7. std::mutex mtx;;
  8. std::unordered_set<crow::websocket::connection*> users;
  9. CROW_ROUTE(app, "/ws")
  10. .websocket()
  11. .onopen([&](crow::websocket::connection& conn){
  12. CROW_LOG_INFO << "new websocket connection";
  13. std::lock_guard<std::mutex> _(mtx);
  14. users.insert(&conn);
  15. })
  16. .onclose([&](crow::websocket::connection& conn, const std::string& reason){
  17. CROW_LOG_INFO << "websocket connection closed: " << reason;
  18. std::lock_guard<std::mutex> _(mtx);
  19. users.erase(&conn);
  20. })
  21. .onmessage([&](crow::websocket::connection& /*conn*/, const std::string& data, bool is_binary){
  22. std::lock_guard<std::mutex> _(mtx);
  23. for(auto u:users)
  24. if (is_binary)
  25. u->send_binary(data);
  26. else
  27. u->send_text(data);
  28. });
  29. CROW_ROUTE(app, "/")
  30. ([]{
  31. char name[256];
  32. gethostname(name, 256);
  33. crow::mustache::context x;
  34. x["servername"] = name;
  35. auto page = crow::mustache::load("ws.html");
  36. return page.render(x);
  37. });
  38. app.port(40080)
  39. .multithreaded()
  40. .run();
  41. }