[Qt-interest] QTcpSocket::waitForReadyRead() "loses" data in a QThread with an event loop

Arnold Krille arnold at arnoldarts.de
Sun Sep 5 19:32:48 CEST 2010


Hi,

On Sunday 05 September 2010 17:27:05 FD wrote:
> I have a QThread with an event loop running which does the network
> handling. Communication with the thread is through signal/slots, which
> works as expected.
> 
> What I am doing now is signaling the thread to do some network
> communication, which consists of sending a command, then reading and
> parsing the results sent by the server. Reading the data consists of
> issuing a waitForReadyRead() and when that returns true, read()ing 50
> bytes at a time as long as read returns some bytes (or the buffer is
> filled by read()). I repeat this until the server response is complete. Of
> course read() will return 0 bytes read at some point, even though the
> server response is not complete.
> 
> Problem: Parsing/processing is quite fast, so it will go back quickly to
> waitForReadyRead() if more data is expected. This call to
> waitForReadyRead() (as well as a read() without waitForReadyRead()) will
> often return nothing (in the case of waitForReadyRead(), it will wait the
> default timeout of 30 seconds, read() will just return 0), even though
> tcpdump shows, that the server sent more data. This data cannot be
> retrieved. Having delays/longer waits before waitForReadyRead() or read()
> sometimes helps and I can retrieve more data, but not all. It this
> happens, this data can never be read, even if trying to do so forever.
> 
> Why would waitForReadyRead() "never" return, even though the server sent
> data in the meantime? Or why would read() not be able to get data from the
> socket, even though there's clearly more data available? Or is there some
> major flaw in the logic in how I'm using the socket?

waitForReadyRead() waits from the moment you call it for more data. if more 
data arrived between your last read and calling waitFor..., it doesn't return 
immediately.
If your network-messages are delimited by a specific character or string, try 
to peek into the received buffer and parse the answer if it contains the 
delimiter and idle for another round if it doesn't (yet) contain that 
delimiter.

> I know that many say doing the network stuff in a thread isn't necessary,
> but the overall code would be less complicated if it could be done in
> separate threads using asynchronous signal/slots.

That is necessary when you need to buffer the incoming data. But the TCP-
classes already buffer the incoming data. So you can use that...

Have fun,

Arnold
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 198 bytes
Desc: This is a digitally signed message part.
Url : http://lists.qt-project.org/pipermail/qt-interest-old/attachments/20100905/f05a853b/attachment.bin 


More information about the Qt-interest-old mailing list