Home / References / ESP32 Library / AsyncUDP Library
Description
The connected() method is used to check the current connection or binding status of an AsyncUDP object. This method returns a boolean value indicating whether the UDP object is currently active and ready for communication. The connection status is automatically managed by the library and is set to true when the connect() or listen() methods successfully establish a UDP endpoint, and set to false when the object is first constructed or when the close() method is called. This method is essential for verifying that UDP operations can be performed before attempting to send or receive data. It provides a reliable way to monitor the operational state of the UDP object, ensuring that applications can handle connection states appropriately and implement proper error handling and retry mechanisms. The method is particularly useful in network applications where connection stability monitoring is crucial for reliable data transmission.
This page is part of the Comprehensive Guide to the ESP32 Arduino Core Library, accessible on AvantMaker.com.
Syntax and Usage
The connected() method has a simple syntax:
Check connection status:
bool isConnected = udp.connected()Returns the current connection/binding status of the AsyncUDP object.
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.
Arguments
The connected() method takes no arguments.
Return Value
The connected() method returns a bool value representing the current connection state. It returns true if the AsyncUDP object is currently connected (via connect()) or bound to a local port (via listen()), indicating that the UDP object is active and ready for communication operations. It returns false if the AsyncUDP object is not connected or bound, indicating that no UDP endpoint has been established or that the connection has been closed. This status reflects the internal state managed by the library and is automatically updated when connection operations are performed.
Example Code
UDP Connection Status Monitor with Automatic Reconnection
This example demonstrates how to use the connected() method to monitor UDP connection status and implement automatic reconnection logic. The application continuously checks the connection state, handles connection failures gracefully, and provides detailed status reporting for both client and server modes.
How to use this example: Upload this code to your ESP32 and replace the WiFi credentials and server configuration. The application will automatically attempt to establish a UDP connection and monitor its status continuously. Monitor the Serial output to see connection status changes, automatic reconnection attempts, and data transmission logs. The example includes comprehensive connection monitoring, error handling, and statistics tracking to demonstrate proper usage of the connected() method in network applications.
Testing with the listen() example: This connection monitoring example works perfectly with the UDP server example from the listen() method webpage. Upload the server code to one ESP32 and this client code to another ESP32 on the same network. Update the client’s server IP address to match the server’s IP address. The client will automatically send various commands (info, stats, echo, clients) that the server recognizes and responds to, while continuously monitoring connection status using the connected() method.
Setup Instructions for Two-Device Testing:
- Server Setup: Upload the
listen()example code to your first ESP32. Note the IP address shown in the Serial Monitor after WiFi connection. - Client Setup: Upload this
connected()example code to your second ESP32. Update theserverIPvariable with the server’s IP address from step 1. - Expected Behavior: The client will connect and send rotating commands while monitoring connection status. The server will respond to each command, and both devices will show detailed communication logs with connection status monitoring.
/*
* Author: Avant Maker
* Date: June 18, 2025
* Version: 1.0
* License: MIT
*
* Description:
* This example demonstrates how to use the connected() method to monitor UDP
* connection status and implement automatic reconnection logic. The application
* continuously checks the connection state, handles connection failures
* gracefully, and provides detailed status reporting for both client and
* server modes.
*
* How to use this example:
* Upload this code to your ESP32 and replace the WiFi credentials and server
* configuration. The application will automatically attempt to establish a UDP
* connection and monitor its status continuously. Monitor the Serial output to
* see connection status changes, automatic reconnection attempts, and data
* transmission logs. The example includes comprehensive connection monitoring,
* error handling, and statistics tracking to demonstrate proper usage of the
* connected() method in network applications.
*
* 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 <AsyncUDP.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
// UDP configuration - modify based on your setup
IPAddress serverIP(192, 168, 0, 123); // Server IP for client mode
uint16_t serverPort = 1234; // Server port for client mode
uint16_t localPort = 5678; // Local port for server mode
AsyncUDP udpClient; // UDP client instance
AsyncUDP udpServer; // UDP server instance
// Connection monitoring and statistics
struct ConnectionMonitor {
bool clientConnected = false;
bool serverConnected = false;
unsigned long lastClientCheck = 0;
unsigned long lastServerCheck = 0;
unsigned long clientReconnectAttempts = 0;
unsigned long serverReconnectAttempts = 0;
unsigned long clientUptime = 0;
unsigned long serverUptime = 0;
unsigned long clientConnectionTime = 0;
unsigned long serverConnectionTime = 0;
unsigned long clientPacketsSent = 0;
unsigned long clientPacketsReceived = 0;
unsigned long serverPacketsReceived = 0;
unsigned long serverPacketsSent = 0;
} monitor;
// Timing intervals
const unsigned long checkInterval = 2000; // Check connection every 2 seconds
const unsigned long sendInterval = 10000; // Send data every 10 seconds
const unsigned long statsInterval = 30000; // Report stats every 30 seconds
const unsigned long reconnectDelay = 5000; // Wait 5 seconds before reconnecting
void setup() {
Serial.begin(115200);
Serial.println("Starting ESP32 AsyncUDP Connection Status Monitor...");
// Initialize WiFi
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println();
Serial.println("WiFi connected successfully!");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
// Initialize UDP connections
initializeConnections();
Serial.println("Connection monitoring started...");
Serial.println("Use Serial Monitor to observe connection status changes");
}
void checkConnectionStatus(bool forceReport = false) {
unsigned long currentTime = millis();
bool statusChanged = false;
// Check client connection status
bool clientCurrentlyConnected = udpClient.connected();
if (clientCurrentlyConnected != monitor.clientConnected || forceReport) {
monitor.clientConnected = clientCurrentlyConnected;
statusChanged = true;
Serial.print("🔍 Client connection status changed: ");
Serial.println(clientCurrentlyConnected ? "CONNECTED" : "DISCONNECTED");
if (clientCurrentlyConnected) {
monitor.clientConnectionTime = currentTime;
}
}
// Check server connection status
bool serverCurrentlyConnected = udpServer.connected();
if (serverCurrentlyConnected != monitor.serverConnected || forceReport) {
monitor.serverConnected = serverCurrentlyConnected;
statusChanged = true;
Serial.print("🔍 Server connection status changed: ");
Serial.println(serverCurrentlyConnected ? "CONNECTED" : "DISCONNECTED");
if (serverCurrentlyConnected) {
monitor.serverConnectionTime = currentTime;
}
}
// Update uptimes
if (monitor.clientConnected) {
monitor.clientUptime = currentTime - monitor.clientConnectionTime;
}
if (monitor.serverConnected) {
monitor.serverUptime = currentTime - monitor.serverConnectionTime;
}
// Report status if changed or forced
if (statusChanged || forceReport) {
reportConnectionStatus();
}
}
void initializeConnections() {
Serial.println("=== Initializing UDP Connections ===");
// Setup UDP client
setupUDPClient();
// Setup UDP server
setupUDPServer();
// Initial connection status check
checkConnectionStatus(true);
}
void setupUDPClient() {
Serial.print("Setting up UDP client connection to ");
Serial.print(serverIP);
Serial.print(":");
Serial.println(serverPort);
if (udpClient.connect(serverIP, serverPort)) {
Serial.println("✅ UDP client connected successfully!");
monitor.clientConnected = true;
monitor.clientConnectionTime = millis();
// Setup client packet handler
udpClient.onPacket([](AsyncUDPPacket packet) {
handleClientPacket(packet);
});
} else {
Serial.println("❌ UDP client connection failed!");
Serial.print("Error code: ");
Serial.println(udpClient.lastErr());
monitor.clientConnected = false;
monitor.clientReconnectAttempts++;
}
}
void setupUDPServer() {
Serial.print("Setting up UDP server on port ");
Serial.println(localPort);
if (udpServer.listen(localPort)) {
Serial.println("✅ UDP server listening successfully!");
monitor.serverConnected = true;
monitor.serverConnectionTime = millis();
// Setup server packet handler
udpServer.onPacket([](AsyncUDPPacket packet) {
handleServerPacket(packet);
});
} else {
Serial.println("❌ UDP server setup failed!");
Serial.print("Error code: ");
Serial.println(udpServer.lastErr());
monitor.serverConnected = false;
monitor.serverReconnectAttempts++;
}
}
void handleClientPacket(AsyncUDPPacket packet) {
monitor.clientPacketsReceived++;
Serial.println("📥 === Received Server Response ===");
Serial.print(" From: ");
Serial.print(packet.remoteIP());
Serial.print(":");
Serial.println(packet.remotePort());
Serial.print(" Response: ");
Serial.write(packet.data(), packet.length());
Serial.println();
Serial.print(" Connection Status: ");
Serial.println(udpClient.connected() ? "✅ CONNECTED" : "❌ DISCONNECTED");
Serial.println("=== End Server Response ===");
}
void handleServerPacket(AsyncUDPPacket packet) {
monitor.serverPacketsReceived++;
Serial.println("📥 Server received packet:");
Serial.print(" From: ");
Serial.print(packet.remoteIP());
Serial.print(":");
Serial.println(packet.remotePort());
Serial.print(" Data: ");
Serial.write(packet.data(), packet.length());
Serial.println();
// Send response
String responseMsg = "Server Response: Packet #" + String(monitor.serverPacketsReceived);
packet.print(responseMsg);
monitor.serverPacketsSent++;
}
void reportConnectionStatus() {
Serial.println("=== Connection Status Report ===");
Serial.print("Client Status: ");
Serial.print(monitor.clientConnected ? "✅ CONNECTED" : "❌ DISCONNECTED");
if (monitor.clientConnected) {
Serial.print(" (Uptime: ");
Serial.print(monitor.clientUptime / 1000);
Serial.print("s)");
}
Serial.println();
Serial.print("Server Status: ");
Serial.print(monitor.serverConnected ? "✅ CONNECTED" : "❌ DISCONNECTED");
if (monitor.serverConnected) {
Serial.print(" (Uptime: ");
Serial.print(monitor.serverUptime / 1000);
Serial.print("s)");
}
Serial.println();
Serial.print("Client Reconnect Attempts: ");
Serial.println(monitor.clientReconnectAttempts);
Serial.print("Server Reconnect Attempts: ");
Serial.println(monitor.serverReconnectAttempts);
Serial.println("================================");
}
void attemptReconnections() {
// Attempt client reconnection if needed
if (!monitor.clientConnected) {
Serial.println("🔄 Attempting client reconnection...");
monitor.clientReconnectAttempts++;
setupUDPClient();
}
// Attempt server reconnection if needed
if (!monitor.serverConnected) {
Serial.println("🔄 Attempting server reconnection...");
monitor.serverReconnectAttempts++;
setupUDPServer();
}
}
void sendTestData() {
// Send test commands from client if connected
if (monitor.clientConnected) {
// Array of commands that the server recognizes
static int commandIndex = 0;
String commands[] = {
"info", // Request server information
"stats", // Request server statistics
"echo Hello from connection monitor!", // Echo test message
"clients", // Request active clients list
"echo Connection test - packet #" + String(monitor.clientPacketsSent + 1)
};
String commandDescriptions[] = {
"Server Information Request",
"Server Statistics Request",
"Echo Test Message",
"Active Clients List Request",
"Echo Connection Test"
};
int numCommands = sizeof(commands) / sizeof(commands[0]);
String command = commands[commandIndex];
String description = commandDescriptions[commandIndex];
commandIndex = (commandIndex + 1) % numCommands;
if (udpClient.print(command)) {
monitor.clientPacketsSent++;
Serial.println("📤 === Sending Command to Server ===");
Serial.print(" Type: ");
Serial.println(description);
Serial.print(" Command: ");
Serial.println(command);
Serial.println("=== Monitoring Connection Status ===");
} else {
Serial.println("❌ Failed to send command");
}
}
}
void printDetailedStatistics() {
Serial.println("=== Detailed Statistics ===");
Serial.println("Client Statistics:");
Serial.print(" Packets Sent: ");
Serial.println(monitor.clientPacketsSent);
Serial.print(" Packets Received: ");
Serial.println(monitor.clientPacketsReceived);
Serial.print(" Connection Uptime: ");
Serial.print(monitor.clientUptime / 1000);
Serial.println("s");
Serial.print(" Reconnect Attempts: ");
Serial.println(monitor.clientReconnectAttempts);
Serial.println("Server Statistics:");
Serial.print(" Packets Received: ");
Serial.println(monitor.serverPacketsReceived);
Serial.print(" Packets Sent: ");
Serial.println(monitor.serverPacketsSent);
Serial.print(" Connection Uptime: ");
Serial.print(monitor.serverUptime / 1000);
Serial.println("s");
Serial.print(" Reconnect Attempts: ");
Serial.println(monitor.serverReconnectAttempts);
Serial.println("System Information:");
Serial.print(" WiFi Signal: ");
Serial.print(WiFi.RSSI());
Serial.println(" dBm");
Serial.print(" Free Heap: ");
Serial.print(ESP.getFreeHeap());
Serial.println(" bytes");
Serial.print(" Total Uptime: ");
Serial.print(millis() / 1000);
Serial.println("s");
Serial.println("===========================");
}
void loop() {
unsigned long currentTime = millis();
// Check connection status periodically
if (currentTime - monitor.lastClientCheck >= checkInterval) {
monitor.lastClientCheck = currentTime;
checkConnectionStatus();
// Attempt reconnections if needed
if (!monitor.clientConnected || !monitor.serverConnected) {
attemptReconnections();
}
}
// Send test commands periodically
static unsigned long lastSendTime = 0;
if (currentTime - lastSendTime >= sendInterval) {
lastSendTime = currentTime;
sendTestData();
}
// Print detailed statistics periodically
static unsigned long lastStatsTime = 0;
if (currentTime - lastStatsTime >= statsInterval) {
lastStatsTime = currentTime;
printDetailedStatistics();
}
// Small delay to prevent excessive CPU usage
delay(100);
}For more ESP32 development resources and tutorials, visit the All About ESP32 Resources Hub on AvantMaker.com
ESP32 Library Index
- ESP32 WiFi Library
- ESP32 WiFiClient Library
- ESP32 HTTPClient Library
- ESP32 WiFiClientSecure Library
- ESP32 WebServer Library
- ESP32 AsyncUDP Librarry
- Connection Management
- Data Transimission
- Broadcast Multicast
- Network 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!