I am currently trying to read an HTTP response from a socket in C++, but I lack the problem-solving skills to read the whole response.
Think of a socket like a hole in the sky. Occasionally, a few bytes might drop in here and there, but there is nothing we can guarantee with those bytes. To read from the socket, we specify a buffer that should be written to, and the number of bytes to be read.
Here is the issue, though. If you specify the number of bytes to be read bigger than the number of bytes in the HTTP response, the socket will wait indefinitely, time out, and never write the bytes that were read from the socket to the buffer.
If the number of bytes read is too small, the obvious issue is that you are not reading all the data in the response.
The HTTP response does have a Content-Length
header in the headers of the response, but we cannot guarantee the position of the Content-Length
header or the size of all the headers of the response.
The only solution I could think of is reading the response byte by byte until I get to the Content-Length
header and reading the size of Content-Length
after there, however, this solution feels inefficient.
What is the correct approach to read all the bytes in the response?