Home / References / ESP32 Library / WebServer Library
Description
The close()
method in the ESP32 WebServer Library is used to terminate the web server’s operation, closing all active client connections and stopping the server from listening for new requests. This method is essential when you need to free up resources for other tasks or prepare your ESP32 for a reset or deep sleep.
Differences Between the stop()
and close()
Methods
The key difference between the ESP32 WebServer Library’s stop()
and close()
methods lies in their scope and immediacy. The close()
method is designed to provide a comprehensive shutdown, halting the server’s listener and terminating all active client connections instantly, making it ideal for situations where an immediate and complete stop is required.
In contrast, the stop()
method is gentler, as it only prevents new connections while allowing existing ones to finish naturally, offering a gentler approach suited for graceful shutdowns or reconfigurations where ongoing tasks should not be abruptly disrupted. This distinction highlights close()
as the aggressive, all-encompassing option, while stop()
supports a more controlled and gradual cessation of server operations.
Syntax and Usage
The close()
method is straightforward and has only one usage. It is called on an existing WebServer
object to stop the server. Below is the syntax:
- Basic Usage: Stops the web server and closes all active connections. No additional configuration or arguments are required.
Here’s a code snippet demonstrating its use:
WebServer server(80); // Create a WebServer object on port 80
server.begin(); // Start the server
// ... Server runs and handles requests ...
server.close(); // Stop the server and close connections
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 directly on the WebServer
object to terminate its functionality cleanly and efficiently.
Return Value
The close()
method does not return a value. Its purpose is to shut down the server and release associated resources, ensuring no further client requests are processed until begin()
is called again.
Example Codes
Below are examples demonstrating the use of the close()
method.
Example 1: Starting and Stopping a Web Server
This example sets up a basic web server on port 80 that responds with a “Hello from ESP32! Server is running temporarily.” message. After a set period (10 seconds), the server is stopped using close()
. Upload this code to your ESP32, connect to its Wi-Fi network, and access the server via the ESP32’s IP address within the first 10 seconds to see it in action. After that, the server will stop, and connections will no longer be accepted.
/*
* Author: Avant Maker
* Date: February 7, 2025
* Version: 1.0
* License: MIT
*
* Description:
* This example demonstrates how to use ESP32 WebServer Library's
* close() method to stop a ESP32 server.
*
* 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
bool serverRunning = false;
unsigned long serverStartTime = 0;
const unsigned long serverRunDuration = 10000; // Run server for 10 seconds
void setup() {
Serial.begin(115200);
// Connect to Wi-Fi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
// Print the IP address
Serial.print("Connected to WiFi. IP address: ");
Serial.println(WiFi.localIP());
// Define the root URL handler
server.on("/", handleRoot);
// Start the server
server.begin();
serverRunning = true;
serverStartTime = millis();
Serial.println("HTTP server started");
Serial.println("Server will run for 10 seconds");
}
void loop() {
// Check if server is running
if (serverRunning) {
server.handleClient(); // Handle client requests
// Check if it's time to stop the server
if (millis() - serverStartTime > serverRunDuration) {
Serial.println("Shutting down server after 10 seconds");
server.close(); // Stop the server
serverRunning = false;
Serial.println("Server has been shut down");
}
}
}
void handleRoot() {
server.send(200, "text/plain", "Hello from ESP32! Server is running temporarily.");
}
Example 2: On-Demand Server Control
This example shows how to control the server status through a physical button (Boot Button on ESP32 DevKitC V4 Development Board) connected to the ESP32. Pressing the button toggles the server state between running and stopped, demonstrating practical use of the close()
method.
Note: Once the code starts running, you need to push the physical button (Boot Button on ESP32 DevKitC V4 Development Board) to start the Web Server. Push the button again will stop the Web Server.
/*
* Author: Avant Maker
* Date: February 7, 2025
* Version: 1.0
* License: MIT
*
* Description:
* This example shows how to control the server status
* through a physical button connected to the ESP32.
* Pressing the button toggles the server state between
* running and stopped, demonstrating practical
* use of the ESP32 WebServer Library's close() method.
*
* 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
bool serverRunning = false;
// Button pin configuration
const int buttonPin = 0; // GPIO0 for the button
int buttonState = HIGH; // Current state of the button
int lastButtonState = HIGH; // Previous state of the button
unsigned long lastDebounceTime = 0; // Last time the button was toggled
unsigned long debounceDelay = 50; // Debounce time in milliseconds
void setup() {
Serial.begin(115200);
// Initialize the button pin as an input with internal pull-up resistor
pinMode(buttonPin, INPUT_PULLUP);
// Connect to Wi-Fi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
// Print the IP address
Serial.print("Connected to WiFi. IP address: ");
Serial.println(WiFi.localIP());
// Define the root URL handler
server.on("/", handleRoot);
Serial.println("Press the button to start/stop the server");
}
void loop() {
// Read the button state with debouncing
int reading = digitalRead(buttonPin);
if (reading != lastButtonState) {
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > debounceDelay) {
if (reading != buttonState) {
buttonState = reading;
// If the button is pressed (LOW with pull-up)
if (buttonState == LOW) {
// Toggle server state
if (serverRunning) {
Serial.println("Button pressed: Stopping server");
server.close(); // Stop the server
serverRunning = false;
Serial.println("Server has been shut down");
} else {
Serial.println("Button pressed: Starting server");
server.begin(); // Start the server
serverRunning = true;
Serial.println("Server has been started");
Serial.print("Server accessible at http://");
Serial.println(WiFi.localIP());
}
}
}
}
lastButtonState = reading;
// Handle client requests if the server is running
if (serverRunning) {
server.handleClient();
}
}
void handleRoot() {
String html = "<h1>ESP32 WebServer Control</h1>";
html += "<p>Server is currently running. Press the physical button to stop it.</p>";
html += "<p>AvantMaker.com ESP32 WebServer Example</p>";
server.send(200, "text/html", html);
}
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!