diff options
| author | Mistivia <i@mistivia.com> | 2025-01-15 19:12:12 +0800 |
|---|---|---|
| committer | Mistivia <i@mistivia.com> | 2025-01-15 19:12:46 +0800 |
| commit | 4da382953c830a61ae24ccbe95c4241db8788269 (patch) | |
| tree | 31f6d184273274e2660516d1ac1146b5661f20b6 /lib/crow/examples/websocket | |
restore
Diffstat (limited to 'lib/crow/examples/websocket')
| -rw-r--r-- | lib/crow/examples/websocket/example_ws.cpp | 48 | ||||
| -rw-r--r-- | lib/crow/examples/websocket/templates/ws.html | 42 |
2 files changed, 90 insertions, 0 deletions
diff --git a/lib/crow/examples/websocket/example_ws.cpp b/lib/crow/examples/websocket/example_ws.cpp new file mode 100644 index 0000000..173d062 --- /dev/null +++ b/lib/crow/examples/websocket/example_ws.cpp @@ -0,0 +1,48 @@ +#include "crow.h" +#include <unordered_set> +#include <mutex> + + +int main() +{ + crow::SimpleApp app; + + std::mutex mtx;; + std::unordered_set<crow::websocket::connection*> users; + + CROW_ROUTE(app, "/ws") + .websocket() + .onopen([&](crow::websocket::connection& conn){ + CROW_LOG_INFO << "new websocket connection"; + 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); + }); + + CROW_ROUTE(app, "/") + ([]{ + char name[256]; + gethostname(name, 256); + crow::mustache::context x; + x["servername"] = name; + + auto page = crow::mustache::load("ws.html"); + return page.render(x); + }); + + app.port(40080) + .multithreaded() + .run(); +} diff --git a/lib/crow/examples/websocket/templates/ws.html b/lib/crow/examples/websocket/templates/ws.html new file mode 100644 index 0000000..2d38fdf --- /dev/null +++ b/lib/crow/examples/websocket/templates/ws.html @@ -0,0 +1,42 @@ +<!doctype html> +<html> +<head> + <script src="https://code.jquery.com/jquery-3.1.0.min.js"></script> +</head> +<body> + <input id="msg" type="text"></input> + <button id="send"> + Send + </button><BR> + <textarea id="log" cols=100 rows=50> + </textarea> + <script> +var sock = new WebSocket("ws://{{servername}}:40080/ws"); + +sock.onopen = ()=>{ + console.log('open') +} +sock.onerror = (e)=>{ + console.log('error',e) +} +sock.onclose = ()=>{ + console.log('close') +} +sock.onmessage = (e)=>{ + $("#log").val( + e.data +"\n" + $("#log").val()); +} +$("#msg").keypress(function(e){ + if (e.which == 13) + { + sock.send($("#msg").val()); + $("#msg").val(""); + } +}); +$("#send").click(()=>{ + sock.send($("#msg").val()); + $("#msg").val(""); +}); + </script> +</body> +</html> |
