From 748b6f6e2e03bfa8d3749d4fb73c2f20aecd1096 Mon Sep 17 00:00:00 2001 From: Palakis Date: Sun, 12 Feb 2017 19:20:32 +0100 Subject: [PATCH] Protect clients object list with a QMutex --- WSServer.cpp | 17 +++++++++++++++-- WSServer.h | 2 ++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/WSServer.cpp b/WSServer.cpp index af257b3a..e7fbf908 100644 --- a/WSServer.cpp +++ b/WSServer.cpp @@ -30,7 +30,8 @@ QT_USE_NAMESPACE WSServer::WSServer(quint16 port, QObject *parent) : QObject(parent), _wsServer(Q_NULLPTR), - _clients() + _clients(), + _clMutex(QMutex::NonRecursive) { _serverThread = new QThread(); _wsServer = new QWebSocketServer( @@ -49,11 +50,16 @@ WSServer::WSServer(quint16 port, QObject *parent) : WSServer::~WSServer() { _wsServer->close(); + + _clMutex.lock(); qDeleteAll(_clients.begin(), _clients.end()); + _clMutex.unlock(); } void WSServer::broadcast(QString message) { + _clMutex.lock(); + Q_FOREACH(WSRequestHandler *pClient, _clients) { if (Config::Current()->AuthRequired == true && pClient->isAuthenticated() == false) { @@ -63,6 +69,8 @@ void WSServer::broadcast(QString message) pClient->sendTextMessage(message); } + + _clMutex.unlock(); } void WSServer::onNewConnection() @@ -71,9 +79,11 @@ void WSServer::onNewConnection() if (pSocket) { WSRequestHandler *pHandler = new WSRequestHandler(pSocket); - connect(pHandler, &WSRequestHandler::disconnected, this, &WSServer::socketDisconnected); + + _clMutex.lock(); _clients << pHandler; + _clMutex.unlock(); } } @@ -82,7 +92,10 @@ void WSServer::socketDisconnected() WSRequestHandler *pClient = qobject_cast(sender()); if (pClient) { + _clMutex.lock(); _clients.removeAll(pClient); + _clMutex.unlock(); + pClient->deleteLater(); } } \ No newline at end of file diff --git a/WSServer.h b/WSServer.h index f85164fa..7f36a3ef 100644 --- a/WSServer.h +++ b/WSServer.h @@ -21,6 +21,7 @@ with this program. If not, see #include #include +#include #include #include "WSRequestHandler.h" @@ -43,6 +44,7 @@ class WSServer : public QObject private: QWebSocketServer *_wsServer; QList _clients; + QMutex _clMutex; QThread *_serverThread; };