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

How to use QTcpSocket with Threads



  • Hi guys!
    In my applicatin I have three classes (3 Measurement modules) which are communication over TCP.
    All have different IP and Ports. My problem is, that I have errors with data transmission and some sensor values are wrong because reading it needs longer. With waitForReadyRead it works but it blocks the whole communication and I have then problems with the other measurement modules
    I want to use the Sockets with Threads and I have no prior experience with threads in QT.
    I hope you guys can help me.

    Best regards



  • @GCE_ said in How to use QTcpSocket with Threads:

    I want to use the Sockets with Threads and I have no prior experience with threads in QT.

    Why? As you say, threads are indeed difficult, especially for a beginner!

    Qt sockets are asynchronous by nature, meaning they don't block and you can have multiple sockets opened/serviced without one blocking/interfering with another.

    As you say, if you use the waitFor...() calls you will block on that socket, and would indeed need threads to prevent that. Don't use those calls at all! Look at the signals/slots in QTcpSocket/QAbstractSocket and use only those, then you won't need any blocking calls or threads :)



  • @GCE_ Hi, you don't need threads for that, instead of waitForReadyRead()you can use readyRead() signal and read from socket at this time. This will avoid blocking your event loop and freeze your GUI.
    see Fortune Client Example


Log in to reply