Home / References / ESP32 Library / WebServer Library
Description
The handleClient()
method is a crucial function in the ESP32 WebServer library that processes incoming client requests. It checks for new client connections, parses HTTP requests, routes them to the appropriate handler functions, and sends back responses. This method must be called repeatedly in the main loop of your ESP32 program to maintain a responsive web server.
Syntax and Usage
The handleClient()
method is called on an instance of the WebServer class. There is only one way to use this method:
server.handleClient();
Where server
is your initialized WebServer object. This method must be called frequently within the loop()
function of your sketch to process incoming client requests in a timely manner.
For practical applications and examples of this method, please consult the “Example Code” section on this page. This section provides comprehensive guidance to help you better understand and apply the method effectively.
Argument(s)
This method does not require any arguments. It operates on the WebServer instance on which it is called, processing any pending client connections and requests.
Return Value
The handleClient()
method does not return any value (void). It processes incoming client connections and requests internally, executing the appropriate handler functions that have been registered with the server.
Example Codes
Example Code 1: Basic Usage Example
This code demonstrates how to use the ESP32 WebServer Library’s handleClient()
method to create a basic web server. The handleClient()
method is essential for processing incoming client requests, allowing the ESP32 to serve a simple HTML page. This example also shows how to define routes for the root path and handle 404 errors.
To use this code, replace “your-SSID” and “your-PASSWORD” with your Wi-Fi credentials. After uploading the code to your ESP32, open the Serial Monitor to find the assigned IP address. Then, open a web browser and enter the ESP32’s IP address to view the web page. If you enter an incorrect URL, you will see a 404 error page.
/*
* Author: Avant Maker
* Date: March 17, 2025
* Version: 1.0
* License: MIT
*
* Description:
* This example demonstrates how to use ESP32 WebServer Library's
* handleClient() method to create a simple web server on an ESP32
* that serves a basic HTML page. The handleClient() method is
* called in the main loop to process incoming requests.
*
* Code Source:
* This example code is sourced from the Comprehensive Guide
* to the ESP32 Arduino Core Library, accessible on AvantMaker.com.
* For additional code examples and in-depth documentation related to
* the ESP32 Arduino Core Library, please visit:
*
* https://avantmaker.com/home/all-about-esp32-arduino-core-library/
*
* AvantMaker.com, your premier destination for all things
* DIY, AI, IoT, Smart Home, and STEM projects. We are dedicated
* to empowering makers, learners, and enthusiasts with
* the resources they need to bring their innovative ideas to life.
*/
#include <WiFi.h>
#include <WebServer.h>
const char* ssid = "your-SSID"; // Replace with your Wi-Fi SSID
const char* password = "your-PASSWORD"; // Replace with your Wi-Fi password
WebServer server(80); // Create a server on port 80
void setup() {
Serial.begin(115200);
// Connect to WiFi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
// Define server routes
server.on("/", handleRoot);
server.onNotFound(handleNotFound);
// Start the server
server.begin();
Serial.println("HTTP server started");
}
void loop() {
server.handleClient(); // Process incoming client requests
// Other code can run here, but handleClient() needs to be called frequently
}
// Handler for the root path
void handleRoot() {
String html = "<!DOCTYPE html><html><body>";
html += "<h1>ESP32 Web Server</h1>";
html += "<p>Welcome to AvantMaker.com's ESP32 Web Server Example!</p>";
html += "</body></html>";
server.send(200, "text/html", html);
}
// Handler for not found pages
void handleNotFound() {
String message = "File Not Found\n\n";
message += "URI: ";
message += server.uri();
message += "\nMethod: ";
message += (server.method() == HTTP_GET) ? "GET" : "POST";
message += "\nArguments: ";
message += server.args();
message += "\n";
for (uint8_t i = 0; i < server.args(); i++) {
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
}
server.send(404, "text/plain", message);
}
Example Code 2: Advanced Usage Example with Multiple Pages
This code demonstrates how to use the ESP32 WebServer Library’s handleClient()
method to create a more complex web server. It includes multiple web pages, handles GET and POST requests, and controls an LED. The handleClient()
method is used to process various types of client requests, including form submissions and page navigation.
To use this code, replace “your-SSID” and “your-PASSWORD” with your Wi-Fi credentials. After uploading the code to your ESP32, open the Serial Monitor to get the assigned IP address. Open a web browser and enter the ESP32’s IP address. You can navigate to different pages, control the LED by submitting a form, and view an “About” page. If an incorrect URL is entered, a 404 error page will be displayed.
/*
* Author: Avant Maker
* Date: March 17, 2025
* Version: 1.0
* License: MIT
*
* Description:
* This example demonstrates how to use ESP32 WebServer Library's
* handleClient() method create a more complex web server with
* multiple pages and a form that processes POST requests.
* The handleClient() method processes all these different
* types of requests.
*
* Code Source:
* This example code is sourced from the Comprehensive Guide
* to the ESP32 Arduino Core Library, accessible on AvantMaker.com.
* For additional code examples and in-depth documentation related to
* the ESP32 Arduino Core Library, please visit:
*
* https://avantmaker.com/home/all-about-esp32-arduino-core-library/
*
* AvantMaker.com, your premier destination for all things
* DIY, AI, IoT, Smart Home, and STEM projects. We are dedicated
* to empowering makers, learners, and enthusiasts with
* the resources they need to bring their innovative ideas to life.
*/
#include <WiFi.h>
#include <WebServer.h>
const char* ssid = "your-SSID"; // Replace with your Wi-Fi SSID
const char* password = "your-PASSWORD"; // Replace with your Wi-Fi password
WebServer server(80);
// Variables to store LED state
bool ledState = false;
const int ledPin = 2; // Built-in LED on most ESP32 dev boards
void setup() {
Serial.begin(115200);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, ledState);
// Connect to WiFi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
// Define server routes
server.on("/", HTTP_GET, handleRoot);
server.on("/led", HTTP_GET, handleLEDStatus);
server.on("/led", HTTP_POST, handleLEDControl);
server.on("/about", HTTP_GET, handleAbout);
server.onNotFound(handleNotFound);
// Start the server
server.begin();
Serial.println("HTTP server started");
}
void loop() {
server.handleClient(); // Process all incoming client requests
// Other tasks can be performed here, but handleClient() should be called frequently
delay(10); // Small delay to avoid WDT reset
}
// Handler for the root path
void handleRoot() {
String html = "<!DOCTYPE html><html><body>";
html += "<h1>ESP32 Advanced Web Server</h1>";
html += "<p>Welcome to AvantMaker.com's ESP32 Advanced Web Server!</p>";
html += "<ul>";
html += "<li><a href='/led'>Control LED</a></li>";
html += "<li><a href='/about'>About</a></li>";
html += "</ul>";
html += "</body></html>";
server.send(200, "text/html", html);
}
// Handler for the LED status page
void handleLEDStatus() {
String html = "<!DOCTYPE html><html><body>";
html += "<h1>LED Control</h1>";
html += "<p>Current LED state: ";
html += (ledState) ? "ON" : "OFF";
html += "</p>";
html += "<form method='POST' action='/led'>";
html += "<input type='hidden' name='state' value='";
html += (ledState) ? "0" : "1";
html += "'>";
html += "<input type='submit' value='";
html += (ledState) ? "Turn OFF" : "Turn ON";
html += "'>";
html += "</form>";
html += "<p><a href='/'>Back to Home</a></p>";
html += "</body></html>";
server.send(200, "text/html", html);
}
// Handler for LED control (POST request)
void handleLEDControl() {
if (server.hasArg("state")) {
ledState = (server.arg("state") == "1");
digitalWrite(ledPin, ledState);
}
// Redirect back to the LED status page
server.sendHeader("Location", "/led");
server.send(303);
}
// Handler for the About page
void handleAbout() {
String html = "<!DOCTYPE html><html><body>";
html += "<h1>About This Server</h1>";
html += "<p>This is an example ESP32 WebServer created for AvantMaker.com.</p>";
html += "<p>It demonstrates how to use the handleClient() method to process different types of requests.</p>";
html += "<p><a href='/'>Back to Home</a></p>";
html += "</body></html>";
server.send(200, "text/html", html);
}
// Handler for not found pages
void handleNotFound() {
String message = "File Not Found\n\n";
message += "URI: ";
message += server.uri();
message += "\nMethod: ";
message += (server.method() == HTTP_GET) ? "GET" : "POST";
message += "\nArguments: ";
message += server.args();
message += "\n";
for (uint8_t i = 0; i < server.args(); i++) {
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
}
server.send(404, "text/plain", message);
}
Example Code 3: Optimizing handleClient() in a Multitasking Environment
This code demonstrates how to use the ESP32 WebServer Library’s handleClient()
method in a multitasking environment. It shows how to keep the web server responsive while performing other tasks like simulating sensor readings and blinking an LED. The handleClient()
method is crucial for handling client requests without blocking other operations.
To use this code, replace “your-SSID” and “your-PASSWORD” with your Wi-Fi credentials. After uploading the code to your ESP32, open the Serial Monitor to get the assigned IP address. Open a web browser and enter the ESP32’s IP address. You can view simulated sensor data, which updates every 5 seconds, and observe the LED blinking every second. The web server remains responsive due to the non-blocking approach using handleClient()
and millis()
.
/*
* Author: Avant Maker
* Date: March 17, 2025
* Version: 1.0
* License: MIT
*
* Description:
* This example demonstrates how to use ESP32 WebServer Library's
* handleClient() method in a multitasking environment, where
* the ESP32 is handling multiple operations simultaneously.
* We'll use a non-blocking approach to ensure the web server
* remains responsive while performing other tasks.
*
* Code Source:
* This example code is sourced from the Comprehensive Guide
* to the ESP32 Arduino Core Library, accessible on AvantMaker.com.
* For additional code examples and in-depth documentation related to
* the ESP32 Arduino Core Library, please visit:
*
* https://avantmaker.com/home/all-about-esp32-arduino-core-library/
*
* AvantMaker.com, your premier destination for all things
* DIY, AI, IoT, Smart Home, and STEM projects. We are dedicated
* to empowering makers, learners, and enthusiasts with
* the resources they need to bring their innovative ideas to life.
*/
#include <WiFi.h>
#include <WebServer.h>
const char* ssid = "your-SSID"; // Replace with your Wi-Fi SSID
const char* password = "your-PASSWORD"; // Replace with your Wi-Fi password
WebServer server(80);
// Variables for sensor reading simulation
unsigned long lastReadingTime = 0;
const unsigned long readingInterval = 5000; // Read sensor every 5 seconds
float temperature = 22.5;
float humidity = 50.0;
// Variables for LED blinking
unsigned long lastBlinkTime = 0;
const unsigned long blinkInterval = 1000; // Blink every second
bool ledState = false;
const int ledPin = 2;
void setup() {
Serial.begin(115200);
pinMode(ledPin, OUTPUT);
// Connect to WiFi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
// Define server routes
server.on("/", handleRoot);
server.on("/data", handleData);
server.onNotFound(handleNotFound);
// Start the server
server.begin();
Serial.println("HTTP server started");
}
void loop() {
// Handle client requests - this needs to be called frequently for responsive web server
server.handleClient();
// Simulate sensor reading (non-blocking)
unsigned long currentMillis = millis();
if (currentMillis - lastReadingTime >= readingInterval) {
lastReadingTime = currentMillis;
readSensors();
}
// Blink LED (non-blocking)
if (currentMillis - lastBlinkTime >= blinkInterval) {
lastBlinkTime = currentMillis;
ledState = !ledState;
digitalWrite(ledPin, ledState);
}
}
void readSensors() {
// Simulate reading from sensors
temperature = 20.0 + random(100) / 10.0;
humidity = 40.0 + random(300) / 10.0;
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.print("°C, Humidity: ");
Serial.print(humidity);
Serial.println("%");
}
void handleRoot() {
String html = "<!DOCTYPE html><html><body>";
html += "<h1>ESP32 Multi-tasking Web Server</h1>";
html += "<p>Welcome to AvantMaker.com's ESP32 Multi-tasking Web Server!</p>";
html += "<p>This example demonstrates how to keep the server responsive with handleClient() while performing other tasks.</p>";
html += "<p><a href='/data'>View Sensor Data</a></p>";
html += "</body></html>";
server.send(200, "text/html", html);
}
void handleData() {
String html = "<!DOCTYPE html><html><body>";
html += "<h1>Sensor Data</h1>";
html += "<p>Temperature: " + String(temperature) + "°C</p>";
html += "<p>Humidity: " + String(humidity) + "%</p>";
html += "<p>LED State: " + String(ledState ? "ON" : "OFF") + "</p>";
html += "<p><a href='/'>Back to Home</a></p>";
html += "<script>setTimeout(function(){ location.reload(); }, 5000);</script>";
html += "</body></html>";
server.send(200, "text/html", html);
}
void handleNotFound() {
String message = "File Not Found\n\n";
message += "URI: ";
message += server.uri();
message += "\nMethod: ";
message += (server.method() == HTTP_GET) ? "GET" : "POST";
message += "\nArguments: ";
message += server.args();
message += "\n";
for (uint8_t i = 0; i < server.args(); i++) {
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
}
server.send(404, "text/plain", message);
}
ESP32 Library Index
- ESP32 WiFi Library
- ESP32 WiFiClient Library
- ESP32 HTTPClient Library
- ESP32 WiFiClientSecure Library
- ESP32 WebServer Library
- Server Operation
- Client Hnadling
- Routing and Handlers
- Authentication
- Request Information
- Which ESP32 Boards are Recommended for Learners
- How to Copy Codes from AvantMaker.com
- What is SPIFFS and how to upload files to it?
- What is LIttleFS and how to upload files to it?
Ready to experiment and explore more about ESP32? Visit our website’s All About ESP32 Resources Hub, packed with tutorials, guides, and tools to inspire your maker journey. Experiment, explore, and elevate your skills with everything you need to master this powerful microcontroller platform!