AsyncTCP: event-driven TCP sockets on the ESP32
Yes, with limits. You can use the Async TCP library online in Mokxi with nothing to install, and the sketch runs in your browser. Part of it is not simulated, and the notes below say which. The example below, "ESP32 async web server: BME280, slider and relay", runs on the ESP32 DevKit V1.
Built in on Mokxi: #include <AsyncTCP.h> and it builds, with nothing to install. Free, and no account needed.
What Async TCP does
AsyncTCP is the layer under ESPAsyncWebServer, and most people meet it as a dependency they had to install. It can also be used on its own: it gives the ESP32 TCP sockets that call your functions when something happens, rather than a socket you poll. A connection arrives, data comes in, the other side hangs up, an error occurs: each one is a callback.
AsyncServer listens on a port and calls onClient() with a new AsyncClient for each connection. On that client you register onData() for incoming bytes and onDisconnect() for the end, answer with write(), and close() when done. To reach out, an AsyncClient registers onConnect() and onError() and calls connect() with a host and port; connect() returns at once and the callbacks report what happened.
The runnable sketch is a tiny raw HTTP server for the editor’s Web panel plus a client that tries example.com. AsyncServer here gets one Web panel request at a time as raw HTTP bytes, and close() sends the reply. Raw outbound TCP is not simulated, so the client’s connect() ends in onError() and onDisconnect() and the serial monitor explains it.
| Library Manager name | Async TCP |
|---|---|
| Author | ESP32Async |
| Include | #include <AsyncTCP.h> |
| Boards | ESP32-C3, ESP32-C6, Seeed XIAO ESP32-C3, ESP32-C3 SuperMini, Seeed XIAO ESP32-C6, ESP32 DevKit, ESP32-DevKitC V4, LOLIN32 Lite, Wemos D1 R32, Cheap Yellow Display, TTGO T-Display, ESP32-S3-DevKitC-1, Seeed XIAO ESP32-S3, Arduino Nano ESP32 |
| In the simulator | Runs, with a gap the note below names. |
Install it
It builds on ESP32-C3, ESP32-C6, Seeed XIAO ESP32-C3, ESP32-C3 SuperMini, Seeed XIAO ESP32-C6, ESP32 DevKit, ESP32-DevKitC V4, LOLIN32 Lite, Wemos D1 R32, Cheap Yellow Display, TTGO T-Display, ESP32-S3-DevKitC-1, Seeed XIAO ESP32-S3, Arduino Nano ESP32.
In Mokxi it is built in: #include <AsyncTCP.h> and the sketch compiles, with no download, no zip and no Library Manager.
On a real board, install "Async TCP" by ESP32Async from the Arduino IDE’s Library Manager (Sketch, Include Library, Manage Libraries), or add Async TCP to lib_deps in PlatformIO. Mokxi follows the calls of release 3.5.0, so a sketch written here builds there too.
What to know in the simulator: Raw TCP is not simulated, so an outbound connect() ends in onError() and onDisconnect() and says why on Serial. AsyncServer gets one Web panel request at a time, as raw HTTP bytes, and close() sends the reply.
The calls you will use
In the order a sketch meets them.
AsyncServer server(80)
A listening socket on port 80. Nothing is accepted until server.begin().
server.onClient(handleNewClient, nullptr)
Registers the function called with each new AsyncClient pointer. The second argument is passed back to you as arg.
c->onData(handleData, nullptr)
Registers the function that gets each chunk of received bytes, with a pointer and a length. The data is not null-terminated.
c->onData([](void *arg, AsyncClient *c, void *data, size_t len) {
c->write("HTTP/1.1 200 OK\r\n\r\nhi");
c->close();
}, nullptr);c->write("hello")
Queues bytes to send and returns how many were accepted. Large replies may need several writes as space frees up.
c->close()
Closes the connection once queued data has gone. onDisconnect() then runs.
client.onError(handleError, nullptr)
Registers the function told about a failed or broken connection, with an error code that AsyncClient::errorToString() turns into words.
client.connect("example.com", 80)
Starts an outbound connection and returns true if it began. The result arrives later in onConnect() or onError().
server.begin()
Starts listening for connections.
Example: ESP32 async web server: BME280, slider and relay
On the ESP32 DevKit V1. It runs in the browser exactly as printed.
/*
* ESP32 async web server: a page with a BME280's readings, a slider that
* sets an LED's brightness and a button that switches a relay, served by
* ESPAsyncWebServer with nothing in loop().
*
* BME280 VIN -> 3V3, GND -> GND, SDA -> GPIO 21 (D21), SCL -> GPIO 22 (D22)
* LED GPIO 26 (D26) -> 220 ohm -> LED -> GND, dimmed with ledcWrite()
* Relay module IN -> GPIO 27 (D27), VCC -> 5 V, GND -> GND
* (a 5 V module that switches on a 3.3 V high; COM and NO switch
* the 12 V lamp)
*
* Libraries: ESPAsyncWebServer and AsyncTCP (ESP32Async), Adafruit BME280.
*
* The page is a template: the server fills each %NAME% from processor()
* as it sends it, so every load shows the newest readings. The slider and
* the relay button are plain HTML forms, so they work in any browser
* without JavaScript: /slider?value=128 and /relay?state=on answer by
* sending the browser back to the page.
*
* Press Run, wait for the IP on the Serial Monitor, then open the Web panel.
* In Mokxi the network is simulated and the Web panel is the only browser;
* on a real ESP32 any phone on the same WiFi opens http://<the IP>/.
*/
#include <WiFi.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>
const char *SSID = "Mokxi-Lab";
const char *PASSWORD = "breadboard";
const int LED_PIN = 26;
const int RELAY_PIN = 27;
Adafruit_BME280 bme;
AsyncWebServer server(80);
int brightness = 0; // 0 to 255
bool relayOn = false;
const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE html><html><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>ESP32 Async Web Server</title>
<style>body{font-family:sans-serif;text-align:center}td{padding:4px 12px}</style>
</head><body>
<h2>ESP32 Async Web Server</h2>
<table align="center">
<tr><td>Temperature</td><td>%TEMPERATURE% °C</td></tr>
<tr><td>Humidity</td><td>%HUMIDITY% %</td></tr>
<tr><td>Pressure</td><td>%PRESSURE% hPa</td></tr>
</table>
<h3>LED brightness: %BRIGHTNESS%</h3>
<form action="/slider">
<input type="range" name="value" min="0" max="255" value="%BRIGHTNESS%">
<input type="submit" value="Set">
</form>
<h3>Relay: %RELAYSTATE%</h3>
<form action="/relay"><button name="state" value="%RELAYNEXT%">Turn %RELAYNEXT%</button></form>
<p><a href="/">Refresh readings</a></p>
</body></html>
)rawliteral";
// Fills each %PLACEHOLDER% of the page.
String processor(const String &var)
{
if (var == "TEMPERATURE") return String(bme.readTemperature(), 1);
if (var == "HUMIDITY") return String(bme.readHumidity(), 1);
if (var == "PRESSURE") return String(bme.readPressure() / 100.0F, 1);
if (var == "BRIGHTNESS") return String(brightness);
if (var == "RELAYSTATE") return relayOn ? "on" : "off";
if (var == "RELAYNEXT") return relayOn ? "off" : "on";
return String();
}
void setup()
{
Serial.begin(115200);
ledcAttach(LED_PIN, 5000, 8); // 5 kHz PWM, 8 bits: duty 0 to 255
ledcWrite(LED_PIN, brightness);
pinMode(RELAY_PIN, OUTPUT);
digitalWrite(RELAY_PIN, LOW);
if (!bme.begin(0x76)) {
Serial.println("No BME280 at 0x76: check SDA, SCL and the address");
}
WiFi.begin(SSID, PASSWORD);
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();
Serial.print("Open http://");
Serial.println(WiFi.localIP());
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
request->send(200, "text/html", index_html, processor);
});
// /slider?value=0..255 sets the LED's brightness
server.on("/slider", HTTP_GET, [](AsyncWebServerRequest *request) {
if (request->hasParam("value")) {
brightness = constrain(request->getParam("value")->value().toInt(), 0, 255);
ledcWrite(LED_PIN, brightness);
Serial.print("LED brightness ");
Serial.println(brightness);
}
request->redirect("/");
});
// /relay?state=on or off switches the relay
server.on("/relay", HTTP_GET, [](AsyncWebServerRequest *request) {
if (request->hasParam("state")) {
relayOn = request->getParam("state")->value() == "on";
digitalWrite(RELAY_PIN, relayOn ? HIGH : LOW);
Serial.println(relayOn ? "Relay on" : "Relay off");
}
request->redirect("/");
});
// The readings as JSON, for another program to read
server.on("/readings", HTTP_GET, [](AsyncWebServerRequest *request) {
String json = "{\"temperature\":" + String(bme.readTemperature(), 1) +
",\"humidity\":" + String(bme.readHumidity(), 1) +
",\"pressure\":" + String(bme.readPressure() / 100.0F, 1) + "}";
request->send(200, "application/json", json);
});
server.onNotFound([](AsyncWebServerRequest *request) {
request->send(404, "text/plain", "Not found");
});
server.begin();
}
void loop()The sketch is cut short here; the editor has every line of it.
Open it in the editor, wired and ready to run · ESP32 async web server: BME280, slider and relay: the project page
Common errors and how to fix them
Multiple libraries were found for "AsyncTCP.h"
Two copies are installed, usually me-no-dev’s old one and the ESP32Async one, and the build may pick the wrong one for your ESPAsyncWebServer. Remove the old copy from the libraries folder and keep the pair from the same maintainer.
The ESP32 resets with a task watchdog message during a request
Callbacks run on the AsyncTCP task, and a delay() or a long loop inside one blocks every other connection and trips the watchdog. Copy what you need, return quickly, and do the slow work in loop().
Free heap shrinks with every request until the board crashes
Each AsyncClient from onClient() is allocated for you and must be freed. Delete it in its onDisconnect() handler, as the example does with delete c, and never use the pointer after that.
Questions and answers
Do I need AsyncTCP if I only use ESPAsyncWebServer?
Yes on the ESP32, because the web server is built on it; you install it but rarely call it. On the ESP8266 the equivalent is ESPAsyncTCP.
Try Async TCP without installing anything
Open the example, change the sketch, and keep your version in a free account.