From 96eacac87d16f8e134f3ebc883eaf289a3d831b0 Mon Sep 17 00:00:00 2001 From: Rico Antonio Felix Date: Mon, 13 Nov 2017 15:17:05 -0400 Subject: [PATCH] service.cpp: Refactored service code --- includeos/service.cpp | 31 +++++++++++++++++-------------- 1 file changed, 17 insertions(+), 14 deletions(-) diff --git a/includeos/service.cpp b/includeos/service.cpp index d87ed1c..c64e673 100644 --- a/includeos/service.cpp +++ b/includeos/service.cpp @@ -15,12 +15,18 @@ // See the License for the specific language governing permissions and // limitations under the License. +#include #include #include #include -static std::map websockets; -static int idx = 0; +using WebSocket_pool_index = int; +using WebSocket_pool = std::map; + +static http::Server_ptr server; + +static WebSocket_pool_index idx; +static WebSocket_pool websockets; void print_num_clients() { @@ -29,9 +35,9 @@ void print_num_clients() void handle_ws(net::WebSocket_ptr ws) { - // nullptr means the WS attempt failed + // nullptr means the WebSocket attempt failed if(not ws) { - printf("WS failed\n"); + printf("WebSocket connection failed\n"); return; } //printf("WS Connected: %s\n", ws->to_string().c_str()); @@ -51,9 +57,6 @@ void handle_ws(net::WebSocket_ptr ws) idx++; } -#include -std::unique_ptr server; - void Service::start() { // Retreive the stack (configured from outside) @@ -61,7 +64,7 @@ void Service::start() Expects(inet.is_configured()); // Create a HTTP Server and setup request handling - server = std::make_unique(inet.tcp()); + server = http::make_server(inet.tcp()); server->on_request([] (auto req, auto rw) { // We only support get @@ -69,10 +72,10 @@ void Service::start() rw->write_header(http::Not_Found); return; } + // WebSockets go here if(req->uri() == "/") { - auto ws = net::WebSocket::upgrade(*req, *rw); - handle_ws(std::move(ws)); + handle_ws(net::WebSocket::upgrade(*req, *rw)); } else { rw->write_header(http::Not_Found); @@ -82,8 +85,8 @@ void Service::start() // Start listening on port 80 server->listen(80); - Timers::periodic(1s, 1s, - [&inet] (uint32_t) { - print_num_clients(); - }); + // Periodically print number of connected clients + Timers::periodic(1s, 1s, [](uint32_t){ + print_num_clients(); + }); }