开发者

How to properly determine that the end-of-input has been reached in a QTCPSocket?

开发者 https://www.devze.com 2023-01-21 08:22 出处:网络
I have the following code that reads from a QTCPSocket: QString request; while(pSocket->waitForReadyRead())

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 开发者_JAVA技巧that avoids signals is preferred because this is supposed to be happening synchronously in a thread.)


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消