0

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?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Jark
  • 65
  • 1
  • 8
  • 1
    I've answered this exact question [so many times before](https://stackoverflow.com/search?q=user%3A65863+http+pseudo). I've closed your question with links to some of my previous answers. – Remy Lebeau Mar 04 '23 at 22:15
  • 1
    You're mistaken, sockets don't generally wait until the number of bytes you've requested are available, they would normally wait until some bytes arrive then immediately return up to the number of bytes you requested – Alan Birtles Mar 04 '23 at 23:01

0 Answers0