Protect clients object list with a QMutex

This commit is contained in:
Palakis 2017-02-12 19:20:32 +01:00
parent 3bd600ed52
commit 748b6f6e2e
2 changed files with 17 additions and 2 deletions

View File

@ -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<WSRequestHandler *>(sender());
if (pClient) {
_clMutex.lock();
_clients.removeAll(pClient);
_clMutex.unlock();
pClient->deleteLater();
}
}

View File

@ -21,6 +21,7 @@ with this program. If not, see <https://www.gnu.org/licenses/>
#include <QtCore/QObject>
#include <QtCore/QList>
#include <QtCore/QMutex>
#include <QtCore/QByteArray>
#include "WSRequestHandler.h"
@ -43,6 +44,7 @@ class WSServer : public QObject
private:
QWebSocketServer *_wsServer;
QList<WSRequestHandler *> _clients;
QMutex _clMutex;
QThread *_serverThread;
};