diff --git a/Makefile b/Makefile index 8b3a070..258c489 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,4 @@ -EXAMPLE_FILES := HelloWorld EchoServer +EXAMPLE_FILES := HelloWorld EchoServer BroadcastingEchoServer THREADED_EXAMPLE_FILES := HelloWorldThreaded EchoServerThreaded override CXXFLAGS += -std=c++17 -Isrc -IuSockets/src override LDFLAGS += uSockets/*.o -lz diff --git a/examples/BroadcastingEchoServer.cpp b/examples/BroadcastingEchoServer.cpp new file mode 100644 index 0000000..e071c66 --- /dev/null +++ b/examples/BroadcastingEchoServer.cpp @@ -0,0 +1,41 @@ +#include "App.h" + +int main() { + /* ws->getUserData returns one of these */ + struct PerSocketData { + + }; + + /* Very simple WebSocket broadcasting echo server */ + uWS::App().ws("/*", { + /* Settings */ + .compression = uWS::SHARED_COMPRESSOR, + .maxPayloadLength = 16 * 1024, + .idleTimeout = 10, + /* Handlers */ + .open = [](auto *ws, auto *req) { + /* Let's make every connection subscribe to the "broadcast" topic */ + ws->subscribe("broadcast"); + }, + .message = [](auto *ws, std::string_view message, uWS::OpCode opCode) { + /* Simply broadcast every single message we get */ + ws->publish("broadcast", message/*, opCode*/); + }, + .drain = [](auto *ws) { + /* Check getBufferedAmount here */ + }, + .ping = [](auto *ws) { + + }, + .pong = [](auto *ws) { + + }, + .close = [](auto *ws, int code, std::string_view message) { + /* We automatically unsubscribe from any topic here */ + } + }).listen(9001, [](auto *token) { + if (token) { + std::cout << "Listening on port " << 9001 << std::endl; + } + }).run(); +}