Home / References / ESP32 Library / AsyncUDP Library
Description
The onPacket() method is used to register a callback function that will be called automatically whenever a UDP packet is received by the AsyncUDP object. This is the primary mechanism for handling incoming UDP data in an asynchronous, non-blocking manner. When a packet arrives, the registered callback function is invoked with an AsyncUDPPacket object containing all the packet information including data, source/destination addresses, ports, and network interface details.
The method supports two different callback function signatures: a simple callback that takes only the packet parameter, and an extended callback that includes a user-defined argument pointer for additional context. This event-driven approach allows for efficient packet processing without the need for continuous polling, making it ideal for real-time UDP applications, IoT sensor networks, and responsive network services that need to handle incoming data immediately upon arrival.
Syntax and Usage
The onPacket() method has two overloaded versions:
– Simple Callback:
udp.onPacket(callbackFunction)Registers a callback function that takes only an AsyncUDPPacket reference parameter.
– Callback with Argument:
udp.onPacket(callbackFunction, userArgument)Registers a callback function that takes a user-defined argument pointer and an AsyncUDPPacket reference parameter.
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.
This page is part of the Comprehensive Guide to the ESP32 Arduino Core Library, accessible on AvantMaker.com.
Arguments
- cb (AuPacketHandlerFunction) – A callback function with signature
void(AsyncUDPPacket &packet)that will be called when a packet is received. The function receives an AsyncUDPPacket object containing all packet information. - cb (AuPacketHandlerFunctionWithArg) – A callback function with signature
void(void *arg, AsyncUDPPacket &packet)that will be called when a packet is received, including a user-defined argument. - arg (void*) – Optional user-defined argument pointer that will be passed to the callback function. Defaults to NULL if not specified. Useful for passing context or object references to the callback.
Return Value
The onPacket() method does not return a value (void). It simply registers the callback function internally. Once registered, the callback will be automatically invoked whenever a UDP packet is received. The callback function itself receives detailed packet information through the AsyncUDPPacket parameter, including packet data, source and destination addresses, ports, packet length, and network interface information. You can register only one callback function at a time – calling onPacket() again will replace the previously registered callback with the new one.
For more ESP32 development resources and tutorials, visit the All About ESP32 Resources Hub on AvantMaker.com
Example Code
UDP Client with Packet Event Handling and Data Exchange
This example demonstrates how to use the onPacket() method to register a callback function that handles incoming UDP packets. The client connects to a specific server address and port, sets up comprehensive packet handling for incoming responses, and continuously sends data while monitoring connection status and statistics. The callback function processes each received packet, extracting all relevant information and responding appropriately to different message types.
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 detailed packet processing information. The example includes comprehensive error handling, connection monitoring, and statistics tracking to demonstrate proper usage of the onPacket() 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 and packet handling process.
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
onPacket()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 and observe how the onPacket() callback processes each received response in real-time.
/*
* Author: Avant Maker
* Date: June 18, 2025
* Version: 1.0
* License: MIT
*
* Description:
* This example demonstrates how to use the onPacket() method to register a
* callback function that handles incoming UDP packets. The client connects to
* a specific server address and port, sets up comprehensive packet handling
* for incoming responses, and continuously sends data while monitoring
* connection status and statistics. The callback function processes each
* received packet, extracting all relevant information and responding
* appropriately to different message types.
*
* 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 detailed packet
* processing information. The example includes comprehensive error handling,
* connection monitoring, and statistics tracking to demonstrate proper usage
* of the onPacket() 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_wifi_ssid";
const char* password = "your_wifi_password";
// UDP server configuration - must match the listen() server example
IPAddress serverIP(192, 168, 1, 100); // 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 onPacket() 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 using onPacket() method
Serial.println("📋 Registering packet handler callback with onPacket()...");
udp.onPacket([](AsyncUDPPacket packet) {
handleIncomingPacket(packet);
});
Serial.println("✅ Packet handler registered successfully!");
// 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("📥 === PACKET RECEIVED VIA onPacket() CALLBACK ===");
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(" Available: ");
Serial.print(packet.available());
Serial.println(" bytes");
Serial.print(" Type: ");
Serial.println(packet.isBroadcast() ? "Broadcast" :
packet.isMulticast() ? "Multicast" : "Unicast");
Serial.print(" IP Version: ");
Serial.println(packet.isIPv6() ? "IPv6" : "IPv4");
Serial.print(" Interface: ");
Serial.println(packet.interface());
// Extract and display packet data
Serial.print(" Raw Data: ");
Serial.write(packet.data(), packet.length());
Serial.println();
// Parse packet data as string for easier processing
String receivedData = "";
for (size_t i = 0; i < packet.length(); i++) {
receivedData += (char)packet.data()[i];
}
Serial.print(" String Data: ");
Serial.println(receivedData);
// Process specific response types
if (receivedData.startsWith("ECHO: ")) {
Serial.println(" 📢 Echo Response Received!");
String echoContent = receivedData.substring(6);
Serial.print(" Echo Content: ");
Serial.println(echoContent);
} else if (receivedData.startsWith("INFO: ")) {
Serial.println(" ℹ️ Server Information Received!");
String infoContent = receivedData.substring(6);
Serial.print(" Server Info: ");
Serial.println(infoContent);
} else if (receivedData.startsWith("STATS: ")) {
Serial.println(" 📊 Server Statistics Received!");
String statsContent = receivedData.substring(7);
Serial.print(" Server Stats: ");
Serial.println(statsContent);
} else if (receivedData.startsWith("CLIENTS: ")) {
Serial.println(" 👥 Client List Received!");
String clientsContent = receivedData.substring(9);
Serial.print(" Active Clients: ");
Serial.println(clientsContent);
} else if (receivedData.startsWith("BROADCAST: ")) {
Serial.println(" 📡 Broadcast Message Received!");
String broadcastContent = receivedData.substring(11);
Serial.print(" Broadcast Content: ");
Serial.println(broadcastContent);
} else {
Serial.println(" 🔍 Unknown Response Type");
}
// Display packet processing timestamp
Serial.print(" Processed at: ");
Serial.print(millis());
Serial.println(" ms");
// Optional: Send acknowledgment back to server
if (receivedData.indexOf("ack_requested") > -1) {
String ackMsg = "ack Packet received and processed";
udp.print(ackMsg);
Serial.println(" 📤 Acknowledgment sent to server");
}
Serial.println("=== END PACKET PROCESSING ===");
}
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 onPacket() Callback ===");
} 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!