c++ - Receive recv data until end of stream (using HTTP)? -
i'm trying out c++ sockets first time, , i've hit first obstacle. i've send data google using send
function (get / http/1.1\r\n\r\n
), , i'm trying receive response. 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 complete string result += buffer; (int = 0; < resultsize; i++) { if (buffer[i] == '\0') { receive = false; } } } return result;
using buffer size of 256 demonstrate problem, if page contains more bytes i'm receiving in buffer, doesn't receive on first try. i've tried looping until data contains null terminator ('\0'
), doesn't seem work. i've tried checking empty lines ('\r\n'
), doesn't work since there empty line between headers , html content of page.
what have noticed possibly use content-length header solve issue. however, unsure how header, since requires @ least 1 recv call, , if there good, safe , efficient way it. i'm not sure when response doesn't include content-length header, since program stuck in infinite loop.
so if there method allows me repeat recv until end of http stream has been reached, i'd know it.
if me i'd appreciate it!
the correct behavior stop reading when http response data tells stop reading. read response headers first (read until \r\n\r\n
reached), parse headers, , read rest of response body dictated headers, , stop reading when reach end of response dictated headers, or when server closes connection, whichever encountered first. – remy lebeau
Comments
Post a Comment