QUdpSocket::waitForBytesWritten() always returns false.



  • When I do something like this (Qt 4.8):

    @
    QUdpSocket socket;
    socket.connectToHost(address, port);
    socket.write(data, size);
    socket.waitForBytesWritten();
    @

    The call to write() succeeds and returns size, but waitForBytesWritten() always returns false and socket.errorString() yields "Unknown error". Why does this happen and how do I wait for the data to be sent without using an event loop? I can find nothing in the documentation that indicates that waitForBytesWritten() does not work for QUdpSocket.



  • I apologize if this is a silly question with an obvious answer but I still am wondering about this. Thanks!



  • I am experiencing the exact same problem with QTcpSocket.
    In the source code below, the data is successfully sent to the server, but waitForBytesWritten always returns false.

    @
    bool TCPClient::sendData(const char* dataToSend, qint64 bytesToSend)
    {
    QMutexLocker writeMutexLocker(&mWriteMutex);

    Logger::getInstance()->write(LogLevel::Info,
                                "TCPClient::sendData(), bytes: " +
                                QString::number(bytesToSend));
    
    qint64 numBytesSent = mTCPSocket.write(dataToSend, bytesToSend);
    mTCPSocket.flush();
    if(-1 == numBytesSent)
    {
      Logger::getInstance()->write(LogLevel::Info,
                                   "TCPClient::sendData(): ERROR!");
    }
    
    // send synchronously
    bool bytesWrittenStatus = mTCPSocket.waitForBytesWritten(5000);
    if(false == bytesWrittenStatus)
    {
        QString errorString = mTCPSocket.errorString();
        Logger::getInstance()->write(LogLevel::Info,
                                   "TCPClient::sendData(): ERROR! Failed to "
                                   "write to the TCP Socket! " + errorString);
    }
    return bytesWrittenStatus;
    

    }
    @



  • I ran into this problem as well, and for me the reason waitForBytesWritten() failed--even though the correct number of bytes were sent over the socket--was because I was calling it from a thread other than the one which created the socket object.

    Apparently the socket methods that "wait" for I/O states to change are very thread-sensitive, most likely due to the dependence on being in sync with the correct event loop.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.