接收recv数据直到流结束(使用HTTP)? [英] Receive recv data until end of stream (using HTTP)?

查看:551
本文介绍了接收recv数据直到流结束(使用HTTP)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我第一次尝试使用C ++套接字,而且我遇到了第一个障碍。我使用发送函数向Google发送了一些数据( GET / HTTP / 1.1 \\\\\\\ / code>),现在我正在尝试收到回复。我目前的代码:

I'm trying out C++ sockets for the first time, and I've hit my first obstacle. I've send some data to google using the send function (GET / HTTP/1.1\r\n\r\n), and now I'm trying to receive the response. My current code:

char buffer[256];
std::string result = "";

int resultSize = 0;
bool receive = true;
while (receive) {
    resultSize = recv(dataSocket, buffer, sizeof(buffer) - 1, 0);
    buffer[resultSize] = '\0'; // Add NULL terminating character to complete string
    result += buffer;

    for (int i = 0; i < resultSize; i++) {
        if (buffer[i] == '\0') {
            receive = false;
        }
    }
}

return result;

使用256的缓冲区大小来演示问题,即如果页面包含的字节数多于我在缓冲区收到,第一次尝试时没有收到任何内容。我试过循环,直到数据包含一个空终止符('\ 0'),这似乎不起作用。我也尝试检查空行('\\\\ n'),由于标题之间有一个空行,因此效果不佳。页面的HTML内容。

Using a buffer size of 256 to demonstrate the problem, which is that if the page contains more bytes than I'm receiving in my buffer, it doesn't receive everything on the first try. I've tried looping until the data contains a null terminator ('\0'), which doesn't seem to work. I've also tried checking for empty lines ('\r\n'), which doesn't work as well since there is an empty line between the headers and the HTML content of a page.

我注意到的是我可以使用Content-Length标头来解决这个问题。但是,我不确定如何获得该标头,因为它需要至少一个recv调用,并且如果有一个好的,安全有效的方法来执行它。当响应不包含Content-Length标头时,我也不确定该怎么做,因为程序将陷入无限循环。

What I have noticed is that I could possibly use the Content-Length header to solve this issue. However, I would be unsure how to get that header, since it requires at least one recv call, and if there is a good, safe and efficient way to do it. I'm also not sure what to do when the response doesn't include the Content-Length header, since the program will then get stuck in an infinite loop.

所以如果有一种方法允许我重复recv直到达到HTTP流的末尾,我想知道它。

So if there is a method that allows me to repeat recv until the end of a HTTP stream has been reached, I'd like to know about it.

如果有人可以提供帮助我对此很感激!

If anyone could help me with this I'd appreciate it!

推荐答案

正确的行为是在HTTP响应数据告诉您停止阅读。首先读取响应头(读取直到达到 \r\\\
\r\ n
),然后解析头,然后读取其余的响应正如标题所指示的那样,只有当您按照标题指示到达响应的结尾时,或者当服务器关闭连接时,无论先遇到哪一个,都会停止读取。 - Remy Lebeau

The correct behavior is to stop reading when the HTTP response data tells you to stop reading. Read the response headers first (read until \r\n\r\n is reached), then parse the headers, and then read the rest of the response body as dictated by the headers, and stop reading only when you reach the end of the response as dictated by the headers, or when the server closes the connection, whichever is encountered first. – Remy Lebeau

这篇关于接收recv数据直到流结束(使用HTTP)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆