ESP32 Webserver - Client keeps reconnecting after client.stop

User avatar
Vader_Mester
Posts: 300
Joined: Tue Dec 05, 2017 8:28 pm
Location: Hungary
Contact:

ESP32 Webserver - Client keeps reconnecting after client.stop

Postby Vader_Mester » Wed Oct 10, 2018 9:13 am

Hi Guys,

I'm having this issue with one of the webserver examples (turns out most examples are written this way), that even though I send "Connection: close" in the header, and even though I call Client.stop(); the broweser keeps reconnecting, and keeping the Webserver busy, making it unable to connect from a different source (another browser). It only frees the server when I close the Tab in browser.

What I want to do really is that when I send the data to the client, it will stop the client when data send is complete, and closes the connection, making it available for other devices to do it again.

Note that I tried to fix it by moving client.stop() right after the data I send, but the effect is the same.

Thank for the help
Vader[BEN]

Code:

Code: Select all

//Original author
/*********
  Rui Santos
  Complete project details at http://randomnerdtutorials.com  
*********/

// Load Wi-Fi library

//#include <WiFi.h>
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include "Adafruit_Si7021.h"

Adafruit_Si7021 sensor = Adafruit_Si7021();

//WIFI MODES
#define STAmode 1
#define SoftAP  0

#if defined STAmode
// Replace with your network credentials
const char* ssid_pub     = "mySSID";
const char* password_pub = "myPW";

#elif defined SoftAP
const char* ssid_loc     = "ESP32_Tempserver";
const char* password_loc = "serverPW";
IPaddress local_ip(192,168,0,1);
IPaddress gateway(192,168,0,1);
IPaddress subnet(255,255,255,0);
#endif

// Set web server port number to 80
WiFiServer server(80);

// Variable to store the HTTP request
String header;

void setup() {
  Serial.begin(115200);

  // wait for serial port to open
  while (!Serial) {
    delay(10);
  }

  Serial.println("Si7021 test!");
  
  if (!sensor.begin()) {
    Serial.println("Si7021 not derected");
    while (true)
      ;
  }
  Serial.print("Found: ");
  switch(sensor.getModel()) {
    case SI_Engineering_Samples:
      Serial.print("SI engineering samples"); break;
    case SI_7013:
      Serial.print("Si7013"); break;
    case SI_7020:
      Serial.print("Si7020"); break;
    case SI_7021:
      Serial.print("Si7021"); break;
    case SI_UNKNOWN:
    default:
      Serial.print("Unknown");
  }
  Serial.print(" Rev(");
  Serial.print(sensor.getRevision());
  Serial.print(")");
  Serial.print(" Serial No.#"); Serial.print(sensor.sernum_a, HEX); Serial.println(sensor.sernum_b, HEX);

#if defined STAmode
  // Connect to Wi-Fi network with SSID and password
 Serial.print("Connecting to... ");
 Serial.println(ssid_pub);
 WiFi.begin(ssid_pub, password_pub);
 Serial.print("Setting WiFi connection...");

Serial.print("Connecting...");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  // Print local IP address
  Serial.println("");
  Serial.println("WiFi connected.");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  
//IF SoftAP mode is used 
#elif defined SoftAP
  Serial.println("WiFi AP starting")
  Serial.print("SoftAP configuration... ");
  Serial.println(WiFi.softAPConfig(local_ip, gateway, subnet) ? "Ready" : "Messed up");
  Serial.print("Soft-AP setting up ... ");
  Serial.println(WiFi.softAP(ssid_loc, password_loc) ? "Ready" : "Messed up");

  Serial.print("Soft-AP IP address = ");
  Serial.println(WiFi.softAPIP());
#endif
//starting server
  Serial.println("Server start");
  server.begin();

}
void loop(){
 
  WiFiClient client = server.available();   // Listen for incoming clients

  if (client) {                             // If a new client connects,
    Serial.println("New client.");          // print a message out in the serial port
    Serial.println(client.remoteIP());
    String currentLine = "";                // make a String to hold incoming data from the client
    while(client.connected()) {            // loop while the client's connected
      if (client.available()) {             // if there's bytes to read from the client,
        char c = client.read();             // read a byte, then
        Serial.println(c);                    // print it out the serial monitor
        header += c;
        if (c == '\n') {                    // if the byte is a newline character
          // if the current line is blank, you got two newline characters in a row.
          // that's the end of the client HTTP request, so send a response:
          if (currentLine.length() == 0) {
            // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
            // and a content-type so the client knows what's coming, then a blank line:
            client.println("HTTP/1.1 200 OK");
            client.println("Content-type:text/html");
            client.println("Connection: close");
            client.println();
            
            // Display the HTML web page
            client.println("<!DOCTYPE html><html>");
            client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
            client.println("<link rel=\"icon\" href=\"data:,\">");
            // CSS to style the table 
            client.println("<style>body { text-align: center; font-family: \"Trebuchet MS\", Arial;}");
            client.println("table { border-collapse: collapse; width:35%; margin-left:auto; margin-right:auto; }");
            client.println("th { padding: 12px; background-color: #0043af; color: white; }");
            client.println("tr { border: 1px solid #ddd; padding: 12px; }");
            client.println("tr:hover { background-color: #bcbcbc; }");
            client.println("td { border: none; padding: 12px; }");
            client.println(".sensor { color:white; font-weight: bold; background-color: #bcbcbc; padding: 1px; }");
            
            // Web Page Heading
            client.println("</style></head><body><h1>ESP32 TEMP and HUM server</h1>");
            client.println("<table><tr><th>MEASUREMENTS</th><th>VALUE</th></tr>");
            client.println("<tr><td>Celsius</td><td><span class=\"sensor\">");
            client.println(sensor.readTemperature());
            client.println(" *C</span></td></tr>");  
            client.println("<tr><td>Fahrenheit</td><td><span class=\"sensor\">");
            client.println(1.8 * sensor.readTemperature() + 32);
            client.println(" *F</span></td></tr>");       
/*            client.println("<tr><td>Pressure</td><td><span class=\"sensor\">");
            client.println(bme.readPressure() / 100.0F);
            client.println(" hPa</span></td></tr>");
            client.println("<tr><td>Approx. Altitude</td><td><span class=\"sensor\">");
            client.println(bme.readAltitude(SEALEVELPRESSURE_HPA));
            client.println(" m</span></td></tr>"); 
            */
            client.println("<tr><td>Humidity</td><td><span class=\"sensor\">");
            client.println(sensor.readHumidity());
            client.println(" %</span></td></tr>"); 
            client.println("</body></html>");
            
            // The HTTP response ends with another blank line
            client.println();
            client.stop();
            Serial.println("Closing client connection");
            // Break out of the while loop
            break;
          } else { // if you got a newline, then clear currentLine
            currentLine = "";
          }
        } else if (c != '\r') {  // if you got anything else but a carriage return character,
          currentLine += c;      // add it to the end of the currentLine
        }
      }
    }
    // Clear the header variable
    header = "";
    // Close the connection
//    client.stop();
    Serial.println("Waiting for client connection.");
    Serial.println("");
  }
}

Code: Select all

task_t coffeeTask()
{
	while(atWork){
		if(!xStreamBufferIsEmpty(mug)){
			coffeeDrink(mug);
		} else {
			xTaskCreate(sBrew, "brew", 9000, &mug, 1, NULL);
			xSemaphoreTake(sCoffeeRdy, portMAX_DELAY);
		}
	}
	vTaskDelete(NULL);
}

ArtemN
Posts: 13
Joined: Mon Sep 03, 2018 4:20 am

Re: ESP32 Webserver - Client keeps reconnecting after client.stop

Postby ArtemN » Wed Oct 10, 2018 12:13 pm

I try to solve this a couple of week - no results.
after client.stop() command bit in client.available() must be set to false, but it = 1 and client.available = 0 bytes then program spin in while(client.available()) up to "[D][WiFiClient.cpp:452] connected(): Disconnected: RES: 0, ERR: 128" after about 8sec - timeout. it is no a browser problem - my old devices with this code work without this freezes...

User avatar
Vader_Mester
Posts: 300
Joined: Tue Dec 05, 2017 8:28 pm
Location: Hungary
Contact:

Re: ESP32 Webserver - Client keeps reconnecting after client.stop

Postby Vader_Mester » Thu Oct 11, 2018 9:22 am

Actually I have just figured it out!
What I'm doing, is that I store the IP of the first connection, serve the client and try to stop it.
From the console logs, I noticed that the browser is set to keep-alive, although I send a header with a connection: stop.
This bit is strange but this means the browser tries to keep reconnecting.

Console log:

Code: Select all

New client.
192.168.43.1
GET / HTTP/1.1
Host: 192.168.43.223
Connection: keep-alive
Cache-Control: max-age=0
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Linux; Android 8.0.0; PRA-LX1 Build/HUAWEIPRA-LX1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Accept-Encoding: gzip, deflate
Accept-Language: hu-HU,hu;q=0.9,en-US;q=0.8,en;q=0.7

Closing client connection
Waiting for client connection.

Client tried to reconnect! Stopping...
So, I modified the code that before the client is served, I check if it's a reconnection by comparing the client.remoteIP() with the previously stored client IP. If they match, it means that it's a reconnect, and I call client.stop(). If it's different I serve it.

Code: Select all

WiFiClient client = server.available();   // Listen for incoming clients
 
  if (client) {
    if(prevClient == client.remoteIP()) {
      client.setTimeout(2000); 
      client.stop();
      Serial.println("Client tried to reconnect! Stopping...");
      prevClient = IPAddress(0,0,0,0);        
      delay(1000);
    } else {
    prevClient = client.remoteIP();
    client.setTimeout(1000);                  // If a new client connects,
    Serial.println("New client.");          // print a message out in the serial port
    Serial.println(client.remoteIP());
    String currentLine = "";                // make a String to hold incoming data from the client
    .
    .
    .
    .
Only tested it for now with my mobile hotspot, opening a browser page on the phone as well as on the computer (2 different IPs) from both Chrome and Opera, and both worked without issue.

Full code is here:

Code: Select all

//Original author
/*********
  Rui Santos
  Complete project details at http://randomnerdtutorials.com  
*********/

// Load Wi-Fi library

#include <WiFi.h>
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include "Adafruit_Si7021.h"

Adafruit_Si7021 sensor = Adafruit_Si7021();

//SoftAP IP Addresses

//WIFI MODES

#define STAmode 1
#define SoftAP  0

#if defined STAmode
// Replace with your network credentials
const char* ssid_pub     = "mySSID";
const char* password_pub = "myPW";

#elif defined SoftAP
const char* ssid_loc     = "ESP32_Tempserver";
const char* password_loc = "serverPW";
IPAddress local_ip(192,168,0,1);
IPAddress gateway(192,168,0,1);
IPAddress subnet(255,255,255,0);
#endif

// Set web server port number to 80
WiFiServer server(80);
//WiFiClient prevClient = NULL;
IPAddress prevClient(0, 0, 0, 0);

// Variable to store the HTTP request
String header;

void setup() {
  Serial.begin(115200);

  // wait for serial port to open
  while (!Serial) {
    delay(10);
  }

  Serial.println("Si7021 test!");
  
  if (!sensor.begin()) {
    Serial.println("Si7021 not derected");
    while (true)
      ;
  }
  Serial.print("Found: ");
  switch(sensor.getModel()) {
    case SI_Engineering_Samples:
      Serial.print("SI engineering samples"); break;
    case SI_7013:
      Serial.print("Si7013"); break;
    case SI_7020:
      Serial.print("Si7020"); break;
    case SI_7021:
      Serial.print("Si7021"); break;
    case SI_UNKNOWN:
    default:
      Serial.print("Unknown");
  }
  Serial.print(" Rev(");
  Serial.print(sensor.getRevision());
  Serial.print(")");
  Serial.print(" Serial No.#"); Serial.print(sensor.sernum_a, HEX); Serial.println(sensor.sernum_b, HEX);

#if defined STAmode
  // Connect to Wi-Fi network with SSID and password
 Serial.print("Connecting to... ");
 Serial.println(ssid_pub);
 WiFi.begin(ssid_pub, password_pub);
 Serial.print("Setting WiFi connection...");

Serial.print("Connecting...");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  // Print local IP address
  Serial.println("");
  Serial.println("WiFi connected.");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  
//IF SoftAP mode is used 
#elif defined SoftAP
  Serial.println("WiFi AP starting")
  Serial.print("SoftAP configuration... ");
  Serial.println(WiFi.softAPConfig(local_ip, gateway, subnet) ? "Ready" : "Messed up");
  Serial.print("Soft-AP setting up ... ");
  Serial.println(WiFi.softAP(ssid_loc, password_loc) ? "Ready" : "Messed up");

  Serial.print("Soft-AP IP address = ");
  Serial.println(WiFi.softAPIP());
#endif
//starting server
  Serial.println("Server start");
  server.begin();

}
void loop(){
 
  WiFiClient client = server.available();   // Listen for incoming clients
 
  if (client) {
    if(prevClient == client.remoteIP()) {
      client.setTimeout(2000); 
      client.stop();
      Serial.println("Client tried to reconnect! Stopping...");
      prevClient = IPAddress(0,0,0,0);        
      delay(1000);
    } else {
    prevClient = client.remoteIP();
    client.setTimeout(1000);                  // If a new client connects,
    Serial.println("New client.");          // print a message out in the serial port
    Serial.println(client.remoteIP());
    String currentLine = "";                // make a String to hold incoming data from the client
    while(client.connected()) {            // loop while the client's connected
      if (client.available()) {             // if there's bytes to read from the client,
        char c = client.read();             // read a byte, then
        Serial.print(c);                    // print it out the serial monitor
        header += c;
        if (c == '\n') {                    // if the byte is a newline character
          // if the current line is blank, you got two newline characters in a row.
          // that's the end of the client HTTP request, so send a response:
          if (currentLine.length() == 0) {
            // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
            // and a content-type so the client knows what's coming, then a blank line:
            client.println("HTTP/1.1 200 OK");
            client.println("Content-type:text/html");
            client.println("Connection: close");
            client.println();
            
            // Display the HTML web page
            client.println("<!DOCTYPE html><html>");
            client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
            client.println("<link rel=\"icon\" href=\"data:,\">");
            // CSS to style the table 
            client.println("<style>body { text-align: center; font-family: \"Trebuchet MS\", Arial;}");
            client.println("table { border-collapse: collapse; width:35%; margin-left:auto; margin-right:auto; }");
            client.println("th { padding: 12px; background-color: #0043af; color: white; }");
            client.println("tr { border: 1px solid #ddd; padding: 12px; }");
            client.println("tr:hover { background-color: #bcbcbc; }");
            client.println("td { border: none; padding: 12px; }");
            client.println(".sensor { color:white; font-weight: bold; background-color: #bcbcbc; padding: 1px; }");
            
            // Web Page Heading
            client.println("</style></head><body><h1>ESP32 TEMP and HUM server</h1>");
            client.println("<table><tr><th>MEASUREMENTS</th><th>VALUE</th></tr>");
            client.println("<tr><td>Celsius</td><td><span class=\"sensor\">");
            client.println(sensor.readTemperature());
            client.println(" *C</span></td></tr>");  
            client.println("<tr><td>Fahrenheit</td><td><span class=\"sensor\">");
            client.println(1.8 * sensor.readTemperature() + 32);
            client.println(" *F</span></td></tr>");       
/*            client.println("<tr><td>Pressure</td><td><span class=\"sensor\">");
            client.println(bme.readPressure() / 100.0F);
            client.println(" hPa</span></td></tr>");
            client.println("<tr><td>Approx. Altitude</td><td><span class=\"sensor\">");
            client.println(bme.readAltitude(SEALEVELPRESSURE_HPA));
            client.println(" m</span></td></tr>"); 
            */
            client.println("<tr><td>Humidity</td><td><span class=\"sensor\">");
            client.println(sensor.readHumidity());
            client.println(" %</span></td></tr>"); 
            client.println("</body></html>");
            
            // The HTTP response ends with another blank line
            client.println();
            client.stop();
            client.flush();
            Serial.println("Closing client connection");
            // Break out of the while loop
            break;
          } else { // if you got a newline, then clear currentLine
            currentLine = "";
          }
        } else if (c != '\r') {  // if you got anything else but a carriage return character,
          currentLine += c;      // add it to the end of the currentLine
        }
      }
    }
    // Clear the header variable
    header = "";
    // Close the connection
    client.stop();
    Serial.println("Waiting for client connection.");
    Serial.println("");
  }
}
}

Code: Select all

task_t coffeeTask()
{
	while(atWork){
		if(!xStreamBufferIsEmpty(mug)){
			coffeeDrink(mug);
		} else {
			xTaskCreate(sBrew, "brew", 9000, &mug, 1, NULL);
			xSemaphoreTake(sCoffeeRdy, portMAX_DELAY);
		}
	}
	vTaskDelete(NULL);
}

ArtemN
Posts: 13
Joined: Mon Sep 03, 2018 4:20 am

Re: ESP32 Webserver - Client keeps reconnecting after client.stop

Postby ArtemN » Fri Oct 12, 2018 9:58 am

What i can do for use this method in rapid mode? about 20 request in sec?

ArtemN
Posts: 13
Joined: Mon Sep 03, 2018 4:20 am

Re: ESP32 Webserver - Client keeps reconnecting after client.stop

Postby ArtemN » Fri Jan 18, 2019 2:52 am

It seemed that wifi goto in sleep mode. I disable sleep mode after Wifi.begin() and all work fine!

void setup()
{
...
WiFi.begin(ssid, password);
WiFi.setSleep(false);// this code solves my problem
...
}

Who is online

Users browsing this forum: No registered users and 56 guests