如何正确确定 QTCPSocket 中已达到输入结束?
我有以下从 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
唯一确定的方法是当您收到的字节数与您期望的字节数相同时。这通常是通过在数据包的开头发送数据的大小来完成的。首先阅读该内容,然后继续循环,直到读完为止。另一种方法是使用哨兵,这是标记数据结尾的特定字节序列,但这通常会变得混乱。
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.
如果您正在处理类似不包含 Content-Length 的 HTTP 响应的情况,并且您知道发送数据后另一端将关闭连接,那么还有一种替代解决方案。
这之所以有效是因为连接的关闭不会丢弃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.
This works because a close of the connection doesn't discard any buffered data in a QTcpSocket.