If you’ve followed one of the web server projects in the “Learn ESP32 with Arduino IDE” course and your web server stops working (drops connection/crashes) on Google Chrome, here’s how to solve that problem.
Open this link for the new web server code: https://gist.github.com/RuiSantosdotme/d5a9d2536c1470008a850b5e01261fb5
Basically, you’ll need to add a timeout timer in any web server code presented in the course to fix this issue. Here’s the exact lines that you need to insert in any web server example.
Before the setup() (take a look at lines 27 to 32), add the following to define these three variables:
// Current time unsigned long currentTime = millis(); // Previous time unsigned long previousTime = 0; // Define timeout time in milliseconds (example: 2000ms = 2s) const long timeoutTime = 2000;
Add inside the loop() and after the if(client) { (line 62 and 63):
currentTime = millis(); previousTime = currentTime;
Modify the while(client.connected()) { to look like this (line 66 and 67):
while (client.connected() && currentTime - previousTime <= timeoutTime) { currentTime = millis();
That’s it. This problem should be solved by implementing these few lines of code in any web server presented in the course.
Note: this problem only happens in Google Chrome and I think it’s because the web browser leaves a connection open (it’s not a problem with the code, but on how the Chrome web browser works).
With this new code, the ESP32/ESP8266 automatically creates a timeout to close any connection after 2 seconds.
I hope this solves the problem and let me know if it works for you.
Learn more about the ESP32 or ESP8266 GPIOs below:
Regards,
Rui