From ead54d6c374c3a5fe898b04b892e2500c26183f7 Mon Sep 17 00:00:00 2001 From: Benjamin Sergeant Date: Tue, 1 Jan 2019 14:52:14 -0800 Subject: [PATCH] listen job run in its own thread, non blocking --- examples/echo_server/echo_server.cpp | 2 +- ixwebsocket/IXWebSocketServer.cpp | 20 ++++++++++++++++++-- ixwebsocket/IXWebSocketServer.h | 7 ++++++- 3 files changed, 25 insertions(+), 4 deletions(-) diff --git a/examples/echo_server/echo_server.cpp b/examples/echo_server/echo_server.cpp index 2d5dc6b1..16eb979d 100644 --- a/examples/echo_server/echo_server.cpp +++ b/examples/echo_server/echo_server.cpp @@ -66,7 +66,7 @@ int main(int argc, char** argv) return 1; } - server.run(); + server.start(); return 0; } diff --git a/ixwebsocket/IXWebSocketServer.cpp b/ixwebsocket/IXWebSocketServer.cpp index 0213da50..3aa5cfc0 100644 --- a/ixwebsocket/IXWebSocketServer.cpp +++ b/ixwebsocket/IXWebSocketServer.cpp @@ -23,14 +23,15 @@ namespace ix WebSocketServer::WebSocketServer(int port, const std::string& host, int backlog) : _port(port), _host(host), - _backlog(backlog) + _backlog(backlog), + _stop(false) { } WebSocketServer::~WebSocketServer() { - + stop(); } void WebSocketServer::setOnConnectionCallback(const OnConnectionCallback& callback) @@ -112,6 +113,21 @@ namespace ix return std::make_pair(true, ""); } + void WebSocketServer::start() + { + if (_thread.joinable()) return; // we've already been started + + _thread = std::thread(&WebSocketServer::run, this); + } + + // FIXME: we should cancel all the async per connections tasks + void WebSocketServer::stop() + { + _stop = true; + _thread.join(); + _stop = false; + } + void WebSocketServer::run() { std::future f; diff --git a/ixwebsocket/IXWebSocketServer.h b/ixwebsocket/IXWebSocketServer.h index 63c9d446..3750eb4e 100644 --- a/ixwebsocket/IXWebSocketServer.h +++ b/ixwebsocket/IXWebSocketServer.h @@ -28,9 +28,9 @@ namespace ix virtual ~WebSocketServer(); void setOnConnectionCallback(const OnConnectionCallback& callback); + void start(); std::pair listen(); - void run(); // Get all the connected clients std::set> getClients(); @@ -51,9 +51,14 @@ namespace ix std::mutex _logMutex; + std::atomic _stop; + std::thread _thread; + const static std::string kDefaultHost; // Methods + void run(); + void stop(); void handleConnection(int fd); // Logging