Problems with WiFiServer after WiFi Reconnect

I am using the Arduino as a web server and pulling data from a web browser by calling the Arduino's IP address. Apparently this works great until the Arduino reconnects to the WiFi network. After that I get a timeout, if I try to pull the Arduino's data.

#include <SPI.h>
#include <WiFi101.h>

// the IP address for the shield:
IPAddress ip(12,34,56,78);    

char ssid[] = "wifinetwork";   
char pass[] = "correcthorsebatterystaple";

int status = WL_IDLE_STATUS;
int count = 0;
int retries;

WiFiServer server(80);

void setup()
{  
  // Initialize serial and wait for port to open:
  Serial.begin(9600);

  connectToWiFi();

  server.begin();
  Serial.println("Server Started");
}

void loop () {
  count++;
  Serial.println(count);
  WiFiClient client = server.available();

  if(client) {
    Serial.print("Connected to a client : "); 

    if(client.connected()) {
        Serial.println("Response Sent to Client"); 
        client.println("Data"); 
    }  

    delay(5);
    client.stop();
    Serial.println("Client is disconnected");
  }

  if (count > 10) {
    Serial.println("Reconnect to WiFi");
    connectToWiFi();
    server.begin();
    count = 0;
  }

  delay(2000); // Wait for 2 seconds before starting to listen again 
}

void connectToWiFi(){
  WiFi.config(ip);
  retries = 0;

  // attempt to connect to Wifi network:
  do {
    Serial.print("Attempting to connect to SSID: ");
    Serial.println(ssid);
    status = WiFi.begin(ssid, pass);
    retries++;
    delay(2000);
  } while(status != WL_CONNECTED && retries < 3);

  if (WiFi.status() == 3) {
    Serial.println("Connected");
  }
}
  delay(2000); // Wait for 2 seconds before starting to listen again

Do you think google or amazon do that?

Restarting the WiFi connection again every 20 seconds (10 slowed down passes through loop() is NOT necessary. Why do you think you need to do that?

I must assume that the WiFi connection is lost, hence the Arduino shall check and reconnect to the network in a specified time intervall.

Also, this is just a example. Later the Arduino shall only re-establish the WiFi connection every 30 minutes or so.

After I digged into the topic, I found a solution that seems to work for me. I suspect that the problem has to do with stuck sockets, at least other users seem to have a somewhat related problem with the Ethernet shield.

In my scenario above it helps to reset the WiFi with WiFi.end() right before the new connection attempts.

In another scenario that I tested, where the the Arduino shall reconnect, as soon as it's not connected anymore, it helped to stop the client explicitly:

if (WiFi.status() != WL_CONNECTED) {
    Serial.println("WiFi not connected. Retry...");
    connectToWiFi();

    server.begin();
    client.stop(); 
 }

As I understand, client.stop() clears the sockets once again. Anyhow, this works for me (for now) and hopefully this helps future readers.