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 70ef77a5d5
commit 9b82a33aff
3 changed files with 25 additions and 4 deletions

View File

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

View File

@ -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<void> f;

View File

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