我正在编写自己的 HTTP getter 套接字。我在MVC++和winsocket2.h中使用C++ 我能够对套接字进行编程,以连接到所需网站的服务器并发送 HTTP GET 请求。
现在的问题是,在我使用 Keep-alive 连接发送 HTTP GET 请求后,我调用了 recv 函数,它工作正常,除了在检索网站之后,它一直徘徊并等待来自服务器的超时提示或要关闭的连接!!
这需要几秒钟或更短的时间,具体取决于服务器的保持事件超时, 因此,我无法从保持事件的 HTTP 设置中受益。
我怎样才能告诉recv函数在检索网站后停止并将命令返回给我,以便我可以发送另一个HTTP请求,同时避免另一个握手机制。
当我使用非阻塞套接字时,它工作得更快,但我不知道何时停止,我设置了一个 str.rfind("",-1,7) 来停止检索数据。 但是,它的效率不是很高。
有谁知道如何做到这一点,或者当连接保持事件状态时 HTTP 服务器发送的最后一个字符是什么,所以我可以用它作为停止决策。
最好,
萌
最佳答案
检查 Content-Length: xxxxx
header ,并且仅读取 header 后的 xxxxx 字节,以空行终止(流中的 CR-LF-CR-LF)。
更新
如果数据被分块:
Chunked Transfer-Encoding (reference)
...
A chunked message body contains a series of chunks, followed by a line with "0" (zero), followed by optional footers (just like headers), and a blank line. Each chunk consists of two parts:
- a line with the size of the chunk data, in hex, possibly followed by a semicolon and extra parameters you can ignore (none are currently standard), and ending with CRLF.
- the data itself, followed by CRLF.
此外,http://www.w3.org分块传输编码的描述在第 3.6.1 节 @ http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html .
关于c++ - 使用 C++ recv winsocket2 保持 HTTP 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4929016/