Important: Please read the Qt Code of Conduct -

QTcpSocket in QThread Problem In Qt5.1

  • I've created a QThread and in run method i have a QTcpSocket variable. It successfully send data to the client. But when the program exit from run function, and I create another thread with the same socket descriptor it fails to send data. The error is : "Invalid Socket Descriptor". It seems that the first QTcpSocket is not deleted correctly and it uses the port so the second thread with the same port can not open it.
    Please Advice.

  • hello,

    on *nix platforms this error usually maps to the socket API EBADF or EALREADY errors. more on those "here":

    on which specific method call do you get that error? is it QAbstractSocket::connectToHost?
    what do you mean when you say that you are re-using the same socket descriptor?
    do you perform operations on the raw socket file descriptor with e.g. QAbstractSocket::setSocketDescriptor or QAbstractSocket::socketDescriptor? why?

    if you do re-use it like that and provide the same fd for the new QTcpSocket, then the fd is bogus since it has indeed been closed when the last QTcpSocket went out of scope or when (and if) you explicitly called QAbstractSocket::disconnectFromHost.

  • About the socket you create in the QThread: is it allocated on the heap or the stack ? Where exactly do you create it (inside the run function, or in the constructor, is it a member var of your QThread subclass) ? If it is allocated on the heap where and when do you delete it ?

  • I've tested it both with heap and stack and both run with same issue. I've defined it in run method.

  • Ok. If you create the object inside the run method the object is living inside the context of the thread which is managed by your QThread subclass. When the run method ends the thread no longer has a running eventloop. So even if you created the socket on the heap and didn't delete it it won't be able to work since it relies on signals and slots.

    First of I would suggest that you delete the socket when the QThread is done (i.e. its run method ends, no working eventloop). This is of course only neccessary if you created it on the heap. And then create a new socket in the next thread. No need to use socket descriptors for this.

    I'm not sure if its possible to reuse sockets in different threads. You could try to create them in the main thread and then use moveToThread() to shift them from thread to thread. But for this you would have to use the "worker object approach": instead of the subclassing QThread approach.

  • Special thanks :)
    I'll try that.

Log in to reply