简体   繁体   中英

Qt: QSslSocket::bytesWritten() signal is emitted too often

I use this code to transfer a large file through a socket without spikes in memory usage :

    connect(socket, SIGNAL(bytesWritten(qint64)), this, SLOT(refillSocketBuffer(qint64)));
    refillSocketBuffer(128*1024);
}

void FtpRetrCommand::refillSocketBuffer(qint64 bytes)
{
    if (!file->atEnd()) {
        socket->write(file->read(bytes));
    } else {
        socket->disconnectFromHost();
    }
}

This works fine with QTcpSocket , but with an encrypted QSslSocket, the bytesWritten() signal is emitted constantly, which causes my function to write to the socket all the time, way quicker than it can send the data though the socket, so eventually its memory usage goes to 400 MB and the OS kills it.

I just found the answer after some more digging, it was in the documentation actually. It seems that I should use encryptedBytesWritten() for SSL sockets instead:

Note: Be aware of the difference between the bytesWritten() signal and the encryptedBytesWritten() signal. For a QTcpSocket, bytesWritten() will get emitted as soon as data has been written to the TCP socket. For a QSslSocket, bytesWritten() will get emitted when the data is being encrypted and encryptedBytesWritten() will get emitted as soon as data has been written to the TCP socket.

So I needed to change this code:

connect(socket, SIGNAL(bytesWritten(qint64)), this, SLOT(refillSocketBuffer(qint64)));

to this:

if (socket->isEncrypted()) {
    connect(socket, SIGNAL(encryptedBytesWritten(qint64)), this, SLOT(refillSocketBuffer(qint64)));
} else {
    connect(socket, SIGNAL(bytesWritten(qint64)), this, SLOT(refillSocketBuffer(qint64)));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM