问题
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;
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.
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.
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!
回答1:
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
来源:https://stackoverflow.com/questions/32856200/receive-recv-data-until-end-of-stream-using-http