如何正确确定 QTCPSocket 中已达到输入结束?

发布于 2024-09-29 02:12:17 字数 270 浏览 10 评论 0原文

我有以下从 QTCPSocket 读取的代码:

QString request;

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

这段代码的问题是它读取所有输入,然后在最后暂停 30 秒。 (这是默认超时。)

避免长时间超时并检测已到达输入末尾的正确方法是什么? (避免信号的答案是首选,因为这应该在线程中同步发生。)

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.)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

半世晨晓 2024-10-06 02:12:17

唯一确定的方法是当您收到的字节数与您期望的字节数相同时。这通常是通过在数据包的开头发送数据的大小来完成的。首先阅读该内容,然后继续循环,直到读完为止。另一种方法是使用哨兵,这是标记数据结尾的特定字节序列,但这通常会变得混乱。

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.

送舟行 2024-10-06 02:12:17

如果您正在处理类似不包含 Content-Length 的 HTTP 响应的情况,并且您知道发送数据后另一端将关闭连接,那么还有一种替代解决方案。

  1. 使用 socket.setReadBufferSize 确保有足够的读取缓冲区来容纳所有可能发送的数据。
  2. 调用socket.waitForDisconnected等待远程端关闭连接
  3. 使用socket.bytesAvailable作为内容长度

这之所以有效是因为连接的关闭不会丢弃QTcpSocket中的任何缓冲数据。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文