QWebSocket sendTextMessage - Thread error QSocketNotifier cannot be enabled
-
Hello,
I have create a QThread that handle my QWebSocket communcation.
Everything seems to work fine but when I want to user "sendTextMessage" I get this error:
QSocketNotifier: Socket notifiers cannot be enabled or disabled from another thread
I do not really understand why I get it because it seems to me that it is the same thread that have created the QWebsocket and the one called during onConnected.
class WebSocketClient : public QThread { Q_OBJECT public: explicit WebSocketClient(QUrl url, QObject *parent = Q_NULLPTR); virtual void run() { qDebug() << "New Thread started"; m_webSocket = new QWebSocket(); connect(m_webSocket, SIGNAL(connected()), this, SLOT(onConnected())); connect(m_webSocket, SIGNAL(disconnected()), this, SLOT(onDisconnected())); m_webSocket->open(m_url); exec(); } private Q_SLOTS: void onConnected() { qDebug() << QTime::currentTime().toString("hh:mm:ss.zzz") << m_webSocket->requestUrl() << " Connected."; connect(m_webSocket, &QWebSocket::textMessageReceived, this, &WebSocketClient::onTextMessageReceived); m_webSocket->sendTextMessage("test"); //QSocketNotifier: Socket notifiers cannot be enabled or disabled from another thread } void onDisconnected() { qDebug() << QTime::currentTime().toString("hh:mm:ss.zzz") << "onDisconnected:" << m_webSocket->requestUrl() << m_webSocket->errorString(); disconnect(m_webSocket, &QWebSocket::textMessageReceived, this, &WebSocketClient::onTextMessageReceived); m_webSocket->deleteLater(); exit(0); } private: QWebSocket* m_webSocket; QUrl m_url; };
Does someones have a idea :( ?
-
I found that the "run" function is called by the new thread.
But onConnected and onDisconnected are called by the main thread ! (the thread that have created the WebSocketClient instance)It looks like I have to review how the signal and slots are connected.
What is the appropriate way to make the signal stay in the new thread ?Edit: Fixed with:
WebSocketClient mySocket; mySocket->moveToThread(mySocket);
onConnected and on Disconnected was properly called by the new thread.