listen job run in its own thread, non blocking

This commit is contained in:
Benjamin Sergeant 2019-01-01 14:52:14 -08:00
parent b749f3c724
commit ead54d6c37
3 changed files with 25 additions and 4 deletions

View File

@ -66,7 +66,7 @@ int main(int argc, char** argv)
return 1; return 1;
} }
server.run(); server.start();
return 0; return 0;
} }

View File

@ -23,14 +23,15 @@ namespace ix
WebSocketServer::WebSocketServer(int port, const std::string& host, int backlog) : WebSocketServer::WebSocketServer(int port, const std::string& host, int backlog) :
_port(port), _port(port),
_host(host), _host(host),
_backlog(backlog) _backlog(backlog),
_stop(false)
{ {
} }
WebSocketServer::~WebSocketServer() WebSocketServer::~WebSocketServer()
{ {
stop();
} }
void WebSocketServer::setOnConnectionCallback(const OnConnectionCallback& callback) void WebSocketServer::setOnConnectionCallback(const OnConnectionCallback& callback)
@ -112,6 +113,21 @@ namespace ix
return std::make_pair(true, ""); 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() void WebSocketServer::run()
{ {
std::future<void> f; std::future<void> f;

View File

@ -28,9 +28,9 @@ namespace ix
virtual ~WebSocketServer(); virtual ~WebSocketServer();
void setOnConnectionCallback(const OnConnectionCallback& callback); void setOnConnectionCallback(const OnConnectionCallback& callback);
void start();
std::pair<bool, std::string> listen(); std::pair<bool, std::string> listen();
void run();
// Get all the connected clients // Get all the connected clients
std::set<std::shared_ptr<WebSocket>> getClients(); std::set<std::shared_ptr<WebSocket>> getClients();
@ -51,9 +51,14 @@ namespace ix
std::mutex _logMutex; std::mutex _logMutex;
std::atomic<bool> _stop;
std::thread _thread;
const static std::string kDefaultHost; const static std::string kDefaultHost;
// Methods // Methods
void run();
void stop();
void handleConnection(int fd); void handleConnection(int fd);
// Logging // Logging