[Qt-interest] problem using sockets and threads
Thiago Macieira
thiago at kde.org
Wed Feb 9 18:32:12 CET 2011
On Wednesday, 9 de February de 2011 17:05:29 pmqt71 wrote:
> So I could use socket's signal-slots, bytesAvailable, waitForReadyRead
> etc.. to achieve non-blocking I/O, right?
I recommend using signals and slots, bytesAvailable, etc. to achieve non-
blocking I/O. Don't use the waitFor* functions, because they *are* blocking.
If you want non-blocking I/O, don't use blocking funtions.
>
> But I think I should avoid instructions like:
>
> while (pSocket->bytesAvailable() < blockSize) {
> if (!pSocket->waitForReadyRead(timeout)) {
> ...
Correct.
> because a slow client may take time to send the entire message causing
> the other to wait (this is the reason why I was using threads). Of
> course if you have other hints...
It's actually worse. The code above does work for QTcpSocket, but doesn't work
for QSslSocket. The reason it doesn't work for QSslSocket is *because* it
works for QTcpSocket: the latter has a recursion prevention, so that the
readyRead() signal isn't emitted inside the signal emission. Since QSslSocket
requires the signal from the underlying socket in order to decrypt the SSL
datastream, and such signal is never emitted, its own readyRead is not emitted
either and waitForReadyRead will fail.
So never write the code above if there's any chance that you may want to use
QSslSocket in the future (even in unencrypted mode).
And to top it all off, QProcess behaves in a third and different way: it has no
recursion prevention, so it will recurse into your readyRead() slot.
To solve this, simply write:
if (pSocket->bytesAvailable() < blockSize)
return;
--
Thiago Macieira - thiago (AT) macieira.info - thiago (AT) kde.org
Senior Product Manager - Nokia, Qt Development Frameworks
PGP/GPG: 0x6EF45358; fingerprint:
E067 918B B660 DBD1 105C 966C 33F5 F005 6EF4 5358
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 190 bytes
Desc: This is a digitally signed message part.
Url : http://lists.qt-project.org/pipermail/qt-interest-old/attachments/20110209/027b58e9/attachment.bin
More information about the Qt-interest-old
mailing list