Qt World Summit: Register Today!

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
        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()));
    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);
        //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);
        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;

    onConnected and on Disconnected was properly called by the new thread.

Log in to reply