diff --git a/misc/main.cpp b/misc/main.cpp index bf2fa18..76d7990 100644 --- a/misc/main.cpp +++ b/misc/main.cpp @@ -5,32 +5,28 @@ int main(int argc, char **argv) { - // do websockets here - - /* - uWS::App().ws("/*", { - .open = []() { + // here we have it + uWS::App().get("/hello", [](auto *res, auto *req) { + res->end("Hello HTTP!"); + }).ws("/*", { + /*.open = */[](auto *ws, auto *req) { }, - .message = []() { + /*.message = */[](auto *ws, std::string_view message, uWS::OpCode opCode) { + ws->send(message, opCode); + } + /*.drain = []() { }, - .drain = []() { + .ping = []() { + + }, + .pong = []() { }, .close = []() { - } - }).listen().run();*/ - - - - uWS::App().get("/hello", [](auto *res, auto *req) { - res->end("Hello HTTP!"); - }).ws("/*", [](auto *ws, auto *req) { - std::cout << "WebSocket conntected to URL: " << req->getUrl() << std::endl; - }, [](auto *ws, std::string_view message, uWS::OpCode opCode) { - ws->send(message, opCode); + }*/ }).listen(9001, [](auto *token) { if (token) { std::cout << "Listening on port " << 3000 << std::endl; diff --git a/src/App.h b/src/App.h index 911774e..1dc9614 100644 --- a/src/App.h +++ b/src/App.h @@ -28,6 +28,7 @@ #include "libwshandshake.hpp" namespace uWS { + template struct TemplatedApp { private: @@ -51,14 +52,19 @@ public: // construct the websocket cintext? no! on demand! } - // this method creates a new websocket context and attaches it to a path - TemplatedApp &ws(std::string pattern, std::function connectHandler, std::function *, std::string_view, uWS::OpCode)> messageHandler) { + struct WebSocketBehavior { + std::function open = nullptr; + std::function *, std::string_view, uWS::OpCode)> message = nullptr; + }; + + TemplatedApp &ws(std::string pattern, WebSocketBehavior &&behavior) { + // init the websocket context here! uWS::WebSocketContext *webSocketContext = uWS::WebSocketContext::create(uWS::Loop::defaultLoop(), (typename StaticDispatch::SOCKET_CONTEXT_TYPE *) httpContext); - webSocketContext->getExt()->messageHandler = messageHandler; + webSocketContext->getExt()->messageHandler = behavior.message; - return get(pattern, [webSocketContext, this, connectHandler](auto *res, auto *req) { + return get(pattern, [webSocketContext, this, behavior](auto *res, auto *req) { std::string_view secWebSocketKey = req->getHeader("sec-websocket-key"); if (secWebSocketKey.length()) { @@ -91,7 +97,7 @@ public: ); // we should hand the new socket to the handler - connectHandler(webSocket, req); + behavior.open(webSocket, req); } else { @@ -105,6 +111,8 @@ public: }); + + return *this; } TemplatedApp &get(std::string pattern, std::function *, HttpRequest *)> handler) {