WifiESP - No socket available

Hi!

I have come across a bit of a weird error. When my weather station runs, it will run fine for any period of time between ten minutes and seventeen hours. Somewhere in that interval, something goes wrong and it just says "[WiFiEsp] No socket available" whenever it tries to send data.

A bit of googling told me that I should close the connection properly, which I was already doing. I also found that I could try to flush the connection, disconnect from the network and read all available data from the ESP8266, which I have done by having the following code in a couple of spots in the code that sends the requests:

  if (!client.connected()) {
    if (debug) {
      Serial.println();
      Serial.println("Disconnecting from server...");
    }
    client.flush();
    client.stop();
    status = WiFi.disconnect();

  }
  while (client.connected()) {
    while (client.available()) {
      char ch = client.read();
      if (debug) {
        Serial.write(ch);
      }
    }
  }

That hasn't worked so far...

Could someone help me spot what I have done wrong, or help me with a suggestion as to what the issue could be?

Here is my full code (on Pastebin because it is too long):

Regards,
Oskar

I use this on an ethernet (w5100). This doesn't have a timeout, so the possibility exists that the "while(client.connected()" loop could become an endless loop if the connection fails or the server stalls.

  while (client.connected()) {
    while (client.available()) {
      char ch = client.read();
      if (debug) {
        Serial.write(ch);
      }
    }
  }
  client.stop();

If you want to see code with a timeout:
http://playground.arduino.cc/Code/WebClient
Pay attention to the connectLoop variable.

Thanks for the answer!

The problem is that the program keeps on running after I get this issue, it keeps on running as normal with the addition of this message after every request.

Post the entire sketch.

The entire sketch is posted on paste in and is linked in the bottom of my original post. It is posted there because it is too long for the forum (600+ lines).