Skip to content

HTTP client gets randomly stuck, with its stream's available() returning 0 almost forever #5139

Closed
@teo1978

Description

@teo1978

I have the following code (I have simplified it to post it here) that downloads a file from an URL and streams it to some physical output.

I read the downloaded data a few bytes at a time and use it as I download it beacause it's to big to store into the RAM (around 250 kB).

  uint8_t httpbuf[128] = {0};
  
  HTTPClient http;
  
  String url="http://some.url/";
  
  int httpcode=200;
  int len=0;
  
  http.begin(url);
  httpcode=http.GET();
  WiFiClient* httpstream = http.getStreamPtr();
  if (httpcode==200) {
    len=http.getSize();
  
    while (len > 0 || len ==-1) {
      int gotbytes=0;
    
      if (!http.connected()) {
        break;
      }
    
      size_t avl=httpstream->available();
      
      if (avl) {
        gotbytes = httpstream->readBytes(httpbuf, ((avl>sizeof(httpbuf))?sizeof(httpbuf):avl));
        Serial.println("Got some bytes");
      }
      else {
        Serial.println("No bytes available");
        delay(100); // can change this to any value, the result doesn't change.
      }
      if (gotbytes>0) {
        if (len>0) len=max(0, len-gotbytes);
        
        // use the data in httpbuf to generate some sort of physical output
        
      }
    }
    
    
  }
  else {
    // http error
  }

What happens is that often, randomly, httpstream->available() starts returning always 0 for very long periods of time.

This is not a network issue or a server issue, as I have never, ever observed anything like this on any kind of http client before.

The expected output would be lots of Got some bytes and some No bytes available from time to time, eventually resulting in downloading the whole file.

The observed result is either:

  1. I start getting dozens of consecutive No bytes available, with some Got some bytes from time to time, so the download is extremely slow, but eventually succesfully finishes, or it suddenly "wakes up" and resume normal speed (i.e. I stop getting "No bytes available" and get mostly "got some bytes" until the end)
    or
  2. I start getting No bytes available forever, until eventually the connection gets closed, so http.connected() return false and breaks the loop, without finishing the download.

P.S. until this is fixed, suggestions for a workaround would be highly appreciated.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions