Home / References / ESP32 Library / AsyncUDP Library
Description
The connect() method is used to establish a connection to a specific remote UDP endpoint. When called, this method configures the AsyncUDP object to send data to a specific IP address and port combination.
The method initializes the internal UDP control block, starts the UDP task, closes any existing connections, and establishes the new connection parameters. This is particularly useful for UDP client applications that need to send data to a single remote server repeatedly, as it simplifies data transmission by eliminating the need to specify the destination address and port for each packet.
Syntax and Usage
The connect() method has two overloaded versions:
– Connect with IPAddress:
bool success = udp.connect(remoteIP, remotePort)Connects to a remote endpoint using an IPAddress object.
– Connect with ip_addr_t:
bool success = udp.connect(addr, remotePort)Connects to a remote endpoint using a low-level ip_addr_t structure.
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
- remoteIP (IPAddress) – The IP address of the remote UDP endpoint to connect to. Can be IPv4 or IPv6 address.
- addr (const ip_addr_t*) – Pointer to a low-level IP address structure for the remote endpoint.
- remotePort (uint16_t) – The port number of the remote UDP endpoint. Valid range is 1-65535.
For more ESP32 development resources and tutorials, visit the All About ESP32 Resources Hub on AvantMaker.com
Return Value
The connect() method returns a bool value indicating the success of the connection attempt. It returns true if the connection was established successfully, meaning the UDP task started properly, the internal UDP control block was initialized, and the remote endpoint parameters were set correctly. It returns false if any error occurred during the connection process, such as failure to start the UDP task, inability to initialize the UDP control block, or invalid connection parameters. You can use the lastErr() method to get more detailed error information if the connection fails.
Example Code
UDP Client with Connection Management and Data Exchange
This example demonstrates how to use the connect() method to establish a connection to a remote UDP server and exchange data. The client connects to a specific server address and port, sets up packet handling for incoming responses, and continuously sends data while monitoring connection status and statistics.
How to use this example: Upload this code to your ESP32 and replace the WiFi credentials and server configuration. The client will automatically connect to the specified UDP server and start sending periodic data packets. Monitor the Serial output to see connection status, data transmission logs, and server responses. The example includes comprehensive error handling, connection monitoring, and statistics tracking to demonstrate proper usage of the connect() method in a real-world UDP client application.
Testing with the listen() example: This client example is designed to work 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. The client will automatically connect to the server and exchange various types of messages including echo commands, info requests, and statistics queries. Both devices will show detailed communication logs, making it easy to understand the UDP communication flow.
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
connect()example code to your second ESP32. Update theserverIPvariable with the server’s IP address from step 1. - Testing: Both devices will automatically start communicating. The client sends commands every 5 seconds, and the server responds with appropriate data. Monitor both Serial outputs to see the complete communication flow.
/*
* Author: Avant Maker
* Date: June 18, 2025
* Version: 1.0
* License: MIT
*
* Description:
* This example demonstrates how to use the connect() method to establish a
* connection to a remote UDP server and exchange data. The client connects to
* a specific server address and port, sets up packet handling for incoming
* responses, and continuously sends data while monitoring connection status
* and statistics.
*
* How to use this example:
* Upload this code to your ESP32 and replace the WiFi credentials and server
* configuration. The client will automatically connect to the specified UDP
* server and start sending periodic data packets. Monitor the Serial output
* to see connection status, data transmission logs, and server responses.
* The example includes comprehensive error handling, connection monitoring,
* and statistics tracking to demonstrate proper usage of the connect()
* method in a real-world UDP client application.
*
* 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 server configuration - must match the listen() server example
IPAddress serverIP(192, 168, 0, 123); // Change to your server ESP32 IP
uint16_t serverPort = 1234; // Must match server port (same as listen() example)
AsyncUDP udp;
// Connection and statistics tracking
struct ConnectionStats {
unsigned long totalPacketsSent = 0;
unsigned long totalPacketsReceived = 0;
unsigned long totalBytesSent = 0;
unsigned long totalBytesReceived = 0;
unsigned long connectionAttempts = 0;
unsigned long lastConnectionTime = 0;
unsigned long connectionUptime = 0;
bool isConnected = false;
} stats;
// Timing control
unsigned long lastSendTime = 0;
unsigned long lastStatsReport = 0;
const unsigned long sendInterval = 5000; // Send data every 5 seconds
const unsigned long statsInterval = 30000; // Report stats every 30 seconds
void setup() {
Serial.begin(115200);
Serial.println("Starting ESP32 AsyncUDP Client with connect() method...");
// 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());
Serial.print("Signal strength: ");
Serial.print(WiFi.RSSI());
Serial.println(" dBm");
// Attempt to connect to UDP server
connectToServer();
}
void connectToServer() {
Serial.println("=== Attempting UDP Connection ===");
Serial.print("Connecting to server: ");
Serial.print(serverIP);
Serial.print(":");
Serial.println(serverPort);
stats.connectionAttempts++;
// Attempt connection using connect() method
if (udp.connect(serverIP, serverPort)) {
Serial.println("✅ UDP connection established successfully!");
stats.isConnected = true;
stats.lastConnectionTime = millis();
// Set up packet handler for incoming responses
udp.onPacket([](AsyncUDPPacket packet) {
handleIncomingPacket(packet);
});
// Send initial connection message
String welcomeMsg = "echo Client connected from " + WiFi.localIP().toString();
if (udp.print(welcomeMsg)) {
Serial.println("📤 Initial connection message sent");
stats.totalPacketsSent++;
stats.totalBytesSent += welcomeMsg.length();
}
} else {
Serial.println("❌ UDP connection failed!");
Serial.print("Last error code: ");
Serial.println(udp.lastErr());
stats.isConnected = false;
// Retry connection after delay
Serial.println("Will retry connection in 10 seconds...");
delay(10000);
connectToServer();
}
}
void handleIncomingPacket(AsyncUDPPacket packet) {
stats.totalPacketsReceived++;
stats.totalBytesReceived += packet.length();
Serial.println("📥 Received server response:");
Serial.print(" From: ");
Serial.print(packet.remoteIP());
Serial.print(":");
Serial.println(packet.remotePort());
Serial.print(" To: ");
Serial.print(packet.localIP());
Serial.print(":");
Serial.println(packet.localPort());
Serial.print(" Length: ");
Serial.print(packet.length());
Serial.println(" bytes");
Serial.print(" Type: ");
Serial.println(packet.isBroadcast() ? "Broadcast" :
packet.isMulticast() ? "Multicast" : "Unicast");
Serial.print(" Response: ");
Serial.write(packet.data(), packet.length());
Serial.println();
Serial.println("=== End Server Response ===");
}
void sendPeriodicData() {
if (!stats.isConnected || !udp.connected()) {
Serial.println("⚠️ Connection lost, attempting to reconnect...");
stats.isConnected = false;
connectToServer();
return;
}
// Array of different commands to test server functionality
static int commandIndex = 0;
String commands[] = {
"info", // Request server information
"stats", // Request server statistics
"echo Hello from ESP32 client!", // Echo test message
"clients", // Request active clients list
"broadcast", // Trigger server broadcast
"echo Sensor data: Temp=23.5C Hum=65%" // Echo with sensor simulation
};
String commandDescriptions[] = {
"Server Information Request",
"Server Statistics Request",
"Echo Test Message",
"Active Clients List Request",
"Broadcast Trigger Request",
"Echo Sensor Data Simulation"
};
int numCommands = sizeof(commands) / sizeof(commands[0]);
String message = commands[commandIndex];
String description = commandDescriptions[commandIndex];
commandIndex = (commandIndex + 1) % numCommands;
// Send command using write() method (uses connected endpoint)
size_t sentBytes = udp.print(message);
if (sentBytes > 0) {
stats.totalPacketsSent++;
stats.totalBytesSent += sentBytes;
Serial.println("📤 === Sending Command to Server ===");
Serial.print(" Type: ");
Serial.println(description);
Serial.print(" Command: ");
Serial.println(message);
Serial.print(" Size: ");
Serial.print(sentBytes);
Serial.println(" bytes");
Serial.println("=== Waiting for Server Response ===");
} else {
Serial.println("❌ Failed to send command");
Serial.print("Last error: ");
Serial.println(udp.lastErr());
}
}
void reportStatistics() {
Serial.println("📊 === CONNECTION STATISTICS ===");
Serial.print("Connection Status: ");
Serial.println(stats.isConnected ? "Connected ✅" : "Disconnected ❌");
Serial.print("Server: ");
Serial.print(serverIP);
Serial.print(":");
Serial.println(serverPort);
Serial.print("Connection Attempts: ");
Serial.println(stats.connectionAttempts);
if (stats.isConnected) {
stats.connectionUptime = millis() - stats.lastConnectionTime;
Serial.print("Connection Uptime: ");
Serial.print(stats.connectionUptime / 1000);
Serial.println(" seconds");
}
Serial.print("Packets Sent: ");
Serial.println(stats.totalPacketsSent);
Serial.print("Packets Received: ");
Serial.println(stats.totalPacketsReceived);
Serial.print("Bytes Sent: ");
Serial.println(stats.totalBytesSent);
Serial.print("Bytes Received: ");
Serial.println(stats.totalBytesReceived);
// Calculate transmission rates
if (stats.connectionUptime > 0) {
float packetsPerSecond = (float)stats.totalPacketsSent / (stats.connectionUptime / 1000.0);
float bytesPerSecond = (float)stats.totalBytesSent / (stats.connectionUptime / 1000.0);
Serial.print("Average Packets/sec: ");
Serial.println(packetsPerSecond, 2);
Serial.print("Average Bytes/sec: ");
Serial.println(bytesPerSecond, 2);
}
// System information
Serial.print("Free Heap: ");
Serial.print(ESP.getFreeHeap());
Serial.println(" bytes");
Serial.print("WiFi Signal: ");
Serial.print(WiFi.RSSI());
Serial.println(" dBm");
Serial.println("================================");
}
void loop() {
unsigned long currentTime = millis();
// Send periodic commands
if (currentTime - lastSendTime >= sendInterval) {
lastSendTime = currentTime;
sendPeriodicData();
}
// Report statistics periodically
if (currentTime - lastStatsReport >= statsInterval) {
lastStatsReport = currentTime;
reportStatistics();
}
// Monitor WiFi connection
if (WiFi.status() != WL_CONNECTED) {
Serial.println("⚠️ WiFi connection lost! Attempting reconnection...");
WiFi.reconnect();
delay(5000);
}
// Small delay to prevent overwhelming the system
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!