Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Writing to a socket from one thread and reading from another



  • Hello all,

    i am new to qt and trying to implement client server program. At client side I want to write from one thread(main) and read socket from another, but I get following notification.

    QSocketNotifier: Socket notifiers cannot be enabled or disabled from another thread
    [ Tue Jan 8 15:21:19 2019] SW Update File Transfered"

    It do reads the socket but it gives this notifciation. Do I have to worry about it or just ignore it?

    the code is as follows.

    tcp_client.h

    namespace Ui {
    class TCP_Client;
    }
    
    class TCP_Client : public QMainWindow
    {
    Q_OBJECT
    public:
    explicit TCP_Client(QWidget *parent = nullptr);
    MyThread *mThread;
    ~TCP_Client();
    private slots:
    void on_pushButton__SW_Update_clicked();
    public:
    Ui::TCP_Client *ui;
    TCP_clientClass *client;
    };
    

    tcp_client.cpp

    void on_pushButton__SW_Update_clicked{  
    /*some work done here*/
     client->tcpSocket->write(buffer,16);
     mThread = new MyThread(client->tcpSocket,this);
     mThread->start();
    }
    

    mythread.h

    class MyThread : public QThread
    {  
    Q_OBJECT
    public:
        explicit MyThread(QTcpSocket *ID, QObject *parent =0);
        void run ();
        bool Stop;
    signals :
        void NumberChanged(QByteArray a);
    public slots : 
    private:
        QTcpSocket *socket1;
        };
    

    mythread.cpp

    MyThread::MyThread(QTcpSocket *ID,QObject *parent) : QThread(parent)
    {
    socket1 = new QTcpSocket();
    socket1=ID;
    }  
    
    void MyThread::run()
    {
    QByteArray a;
    qDebug()<<"Inside running thread";
    socket1->waitForReadyRead(-1);
    a= socket1->readAll();
    qDebug() << a;
    }
    

    Basically, I am writing when button is pushed and inside I create a thread so that it can read data sent by server

    [edit: koahnig, code tags added]



  • @bluesparrow

    Hi and welcome to devnet

    What is the reason for handling in different threads?

    In case your assumption is that you do not want to miss incoming data, there is no reason to worry. The in-coming data is buffered until you are retrieving it.

    Typically one may wait for a readyRead signal and read the data, but you may also wait and check bytesAvailable


Log in to reply