ESP32 WiFiClient Library – flush

Home / References / ESP32 Library / WiFiClientSecure

Description

The flush() method in the ESP32 WiFiClient Library clears any remaining data in the input buffer of a network connection. This is a valuable tool for makers working on ESP32 projects that require precise control over network communication. By flushing the buffer, you ensure that no leftover data interferes with subsequent reads, making it ideal for resetting the connection state or preparing for a new data stream.


Syntax and Usage

The flush() method is simple to use and has a single form without arguments. Here’s how you can integrate it into your ESP32 sketches:

client.flush();

This method is called on a WiFiClient object to discard all data currently available in the input buffer. It’s particularly useful after reading partial data from a server or when you need to start fresh with incoming data.

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 input buffer of the WiFiClient object, clearing it without needing additional parameters.


Return Value

The flush() method does not return a value (i.e., it is a void function). Its purpose is to perform an action—clearing the input buffer—rather than providing feedback. After calling flush(), the buffer is emptied, and subsequent calls to available() will reflect that no data is present until new data arrives.


Example Codes

Below is an example demonstrating how to use the flush() method in a practical ESP32 project. This example connects to a test server and uses flush() to clear the input buffer after reading part of the response, ensuring a clean slate for further operations.

Example: Using flush() to Clear the Input Buffer

This sketch connects to www.httpbin.org, sends a GET request, reads the first few bytes of the response, and then uses flush() to discard the remaining data. It’s a practical illustration of how flush() can be used to manage network data effectively.

Explanation: In this example, the ESP32 connects to www.httpbin.org and sends a GET request. The loop() function reads the first 10 bytes of the server’s response and prints them to the Serial Monitor. Then, flush() is called to clear any remaining data in the input buffer. After flushing, the sketch checks if any data remains (which it shouldn’t), demonstrating how flush() ensures the buffer is empty. This is useful in scenarios where you want to discard unwanted data and prepare for a fresh read.

/*
 * Author: Avant Maker
 * Date: February 24, 2025
 * Version: 1.0
 * Description: This sketch connects to www.httpbin.org,
 * sends a GET request, reads the first few bytes of
 * the response, and then uses ESP32 WiFiClient Library's
 * flush method to discard the remaining data.
 * It’s a practical illustration of how flush can
 * be used to manage network data effectively.
 *
 * License: MIT 
 * 
 * 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/references/esp32-arduino-core-index/
 *
 * 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>

// WiFi credentials
const char* ssid = "your-SSID";          // Replace with your Wi-Fi SSID
const char* password = "your-PASSWORD";  // Replace with your Wi-Fi password

// Server details
const char* host = "www.httpbin.org";
const int port = 80;

WiFiClient client;

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

    // Connect to WiFi
    Serial.print("Connecting to ");
    Serial.println(ssid);
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }
    Serial.println("\nWiFi connected");

    // Connect to the server
    Serial.print("Connecting to ");
    Serial.println(host);
    if (client.connect(host, port)) {
        Serial.println("Connected to server");

        // Send a GET request
        client.println("GET /get HTTP/1.1");
        client.println("Host: www.httpbin.org");
        client.println("Connection: close");
        client.println();
    } else {
        Serial.println("Connection failed");
    }
}

void loop() {
    if (client.available()) {
        // Read the first 10 bytes of the response
        Serial.println("Reading first 10 bytes:");
        for (int i = 0; i < 10 && client.available(); i++) {
            char c = client.read();
            Serial.print(c);
        }
        Serial.println();

        // Flush the remaining data
        Serial.println("Flushing remaining data...");
        client.flush();

        // Check if anything is left
        if (client.available()) {
            Serial.println("Data still available (unexpected).");
        } else {
            Serial.println("Buffer successfully flushed.");
        }

        // Wait briefly before closing
        delay(1000);
    }

    // Stop the client when the connection ends
    if (!client.connected()) {
        Serial.println("Disconnected");
        client.stop();
        while (true) delay(1000); // Halt after disconnect
    }
}

ESP32 Library Index

ESP32 Arduino Core Library


FAQ

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!

error: Content is protected !!