QTcpSocket and bytesWritten signal on Windows



  • Hi all,

    I'm writing an application where I use QTcpSocket. I need to know how many bytes have been written so I ended up with something like this:

    void MainWindow::createSocket()
    {
        socket = new QTcpSocket();
        connect(socket, &QTcpSocket::bytesWritten, this, &MainWindow::onBytesWritten);
    }
    
    void MainWindow::sendData(const QString &data)
    {
        socket->write(data.toUtf8());
    }
    
    void MainWindow::onBytesWritten(qint64 bytes)
    {
        m_bytesWritten += bytes;
        qint64 remaining{socket->bytesToWrite()};
        qint64 total{m_bytesWritten + remaining};
    
        if (total != 0)
            qDebug() << (static_cast<int>(static_cast<double>(m_bytesWritten) / total * 100)) << "% written";
    }
    

    I create a socket, set the connections, write data and print the percentage of data written when the signal bytesWritten is emitted by the socket.
    On Linux this works correctly but on Windows, the bytesWritten signal is emitted ONLY ONCE with the bytes value set as the total amount of bytes to write (even when sending very large blocks of data), so the percentage goes directly from 0 to 100%.
    What am I doing wrong?

    Thank You so much for any help
    bye
    riki


  • Lifetime Qt Champion

    Hi,

    AFAIK you're not doing anything wrong. Qt is using the underlying system socket so they might not buffer/report written data the same.



  • Thank You SGaist for your reply.

    Do You know if there is any work around to get to know how many bytes have been really written?
    I think this behaviour has to do with buffers. To the application the data is all sent but the operating system is still sending data to the network device.
    The problem is that if the network connection goes down before the OS has flushed the buffer, the application may not know that some data was not sent to the receiver.


Log in to reply
 

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