Skip to content

Instantly share code, notes, and snippets.

Created November 5, 2023 00:10
Show Gist options
  • Save miceno/1d7fb4f9dcddc5caeffd927aa6f12eee to your computer and use it in GitHub Desktop.
Save miceno/1d7fb4f9dcddc5caeffd927aa6f12eee to your computer and use it in GitHub Desktop.
Persistent TCP server using ESPAsyncTCP and ESP8266Wifi libraries
#include <ESP8266WiFi.h>
#include <ESPAsyncTCP.h>
#define MAX_BAUD_RATE 115200
#define SERVER_HOST_NAME "esp-example"
AsyncServer* server = NULL;
/* clients events */
static void handleError(void* arg, AsyncClient* client, int8_t error) {
Serial.printf("\n connection error %s from client %s \n", client->errorToString(error), client->remoteIP().toString().c_str());
static void handleData(void* arg, AsyncClient* client, void* data, size_t len) {
Serial.printf("\n data received from client %s \n", client->remoteIP().toString().c_str());
Serial.write((uint8_t*)data, len);
// reply to client
if (client->space() > 32 && client->canSend()) {
char reply[32];
sprintf(reply, "this is from %s", SERVER_HOST_NAME);
client->add(reply, strlen(reply));
static void handleDisconnect(void* arg, AsyncClient* client) {
Serial.printf("\n client %s disconnected \n", client->remoteIP().toString().c_str());
static void handleTimeOut(void* arg, AsyncClient* client, uint32_t time) {
Serial.printf("\n client ACK timeout ip: %s \n", client->remoteIP().toString().c_str());
/* server events */
static void handleNewClient(void* arg, AsyncClient* client) {
Serial.printf("\n new client has been connected to server, ip: %s", client->remoteIP().toString().c_str());
// register events
client->onData(&handleData, NULL);
client->onError(&handleError, NULL);
client->onDisconnect(&handleDisconnect, NULL);
client->onTimeout(&handleTimeOut, NULL);
void setup_wifi() {
// WiFi parameters: connect as STA to a Wifi AP
const char* ssid = "YOUR_SSID";
const char* password = "YOUR_PASSWORD";
// Static IP address configuration
IPAddress staticIP(192, 168, 1, 61); //ESP static ip
IPAddress gateway(192, 168, 1, 1); //IP Address of your WiFi Router (Gateway)
IPAddress subnet(255, 255, 255, 0); //Subnet mask
IPAddress dns(8, 8, 8, 8); //DNS
WiFi.disconnect(); // Prevent connecting to wifi based on previous configuration
WiFi.config(staticIP, subnet, gateway);
WiFi.mode(WIFI_STA); // WiFi mode station (connect to wifi router only
WiFi.begin(ssid, password);
// Connect to WiFi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) { // blink to indicate the device is trying to connect to WIFI
Serial.println("WiFi connected");
void setup_serial() {
void setup() {
server = new AsyncServer(TCP_PORT); // start listening on tcp port 7050
server->onClient(&handleNewClient, server);
void loop() {
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment