2016-08-28 05:46:31 +00:00
|
|
|
#include "crow.h"
|
|
|
|
#include <unordered_set>
|
|
|
|
#include <mutex>
|
|
|
|
|
|
|
|
|
|
|
|
int main()
|
|
|
|
{
|
|
|
|
crow::SimpleApp app;
|
|
|
|
|
2021-07-05 18:04:51 +00:00
|
|
|
std::mutex mtx;
|
2016-08-28 05:46:31 +00:00
|
|
|
std::unordered_set<crow::websocket::connection*> users;
|
|
|
|
|
2022-05-06 17:02:43 +00:00
|
|
|
CROW_WEBSOCKET_ROUTE(app, "/ws")
|
2021-11-27 17:44:51 +00:00
|
|
|
.onopen([&](crow::websocket::connection& conn) {
|
|
|
|
CROW_LOG_INFO << "new websocket connection from " << conn.get_remote_ip();
|
|
|
|
std::lock_guard<std::mutex> _(mtx);
|
|
|
|
users.insert(&conn);
|
|
|
|
})
|
|
|
|
.onclose([&](crow::websocket::connection& conn, const std::string& reason) {
|
|
|
|
CROW_LOG_INFO << "websocket connection closed: " << reason;
|
|
|
|
std::lock_guard<std::mutex> _(mtx);
|
|
|
|
users.erase(&conn);
|
|
|
|
})
|
|
|
|
.onmessage([&](crow::websocket::connection& /*conn*/, const std::string& data, bool is_binary) {
|
|
|
|
std::lock_guard<std::mutex> _(mtx);
|
|
|
|
for (auto u : users)
|
|
|
|
if (is_binary)
|
|
|
|
u->send_binary(data);
|
|
|
|
else
|
|
|
|
u->send_text(data);
|
|
|
|
});
|
2016-08-28 05:46:31 +00:00
|
|
|
|
|
|
|
CROW_ROUTE(app, "/")
|
2021-11-27 17:44:51 +00:00
|
|
|
([] {
|
2017-09-17 10:14:40 +00:00
|
|
|
char name[256];
|
|
|
|
gethostname(name, 256);
|
|
|
|
crow::mustache::context x;
|
|
|
|
x["servername"] = name;
|
2021-11-21 16:00:44 +00:00
|
|
|
|
2016-08-28 05:46:31 +00:00
|
|
|
auto page = crow::mustache::load("ws.html");
|
2021-11-27 17:44:51 +00:00
|
|
|
return page.render(x);
|
|
|
|
});
|
2016-08-28 05:46:31 +00:00
|
|
|
|
|
|
|
app.port(40080)
|
2021-11-25 11:45:38 +00:00
|
|
|
.multithreaded()
|
|
|
|
.run();
|
2016-08-28 05:46:31 +00:00
|
|
|
}
|