Question

I have the following code that reads from a QTCPSocket:

QString request;

while(pSocket->waitForReadyRead())
{
    request.append(pSocket->readAll());
}

The problem with this code is that it reads all of the input and then pauses at the end for 30 seconds. (Which is the default timeout.)

What is the proper way to avoid the long timeout and detect that the end of the input has been reached? (An answer that avoids signals is preferred because this is supposed to be happening synchronously in a thread.)

Was it helpful?

Solution

The only way to be sure is when you have received the exact number of bytes you are expecting. This is commonly done by sending the size of the data at the beginning of the data packet. Read that first and then keep looping until you get it all. An alternative is to use a sentinel, a specific series of bytes that mark the end of the data but this usually gets messy.

OTHER TIPS

If you're dealing with a situation like an HTTP response that doesn't contain a Content-Length, and you know the other end will close the connection once the data is sent, there is an alternative solution.

  1. Use socket.setReadBufferSize to make sure there's enough read buffer for all the data that may be sent.
  2. Call socket.waitForDisconnected to wait for the remote end to close the connection
  3. Use socket.bytesAvailable as the content length

This works because a close of the connection doesn't discard any buffered data in a QTcpSocket.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top