Hi i am using Esp32 as websocket server using ESPasynchronus webserver . I need help with the disconnection part .
#include <Arduino.h>
#include <WiFi.h>
#include <ESPAsyncWebServer.h>
// #include <ESPAsyncTCP.h> // For ESP8266
#define WIFI_SSID "SSID"
#define WIFI_PASSWORD "PASS"
AsyncWebServer server(80);
// Set up WebSocket
AsyncWebSocket ws("/ws");
IPAddress local_IP(192, 168, 1, 64);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);
IPAddress primaryDNS(192, 168, 1, 1);
IPAddress secondaryDNS(8, 8, 4, 4);
void setup() {
Serial.begin(115200);
WiFi.mode(WIFI_STA);
WiFi.config(local_IP, gateway, subnet, primaryDNS, secondaryDNS);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED) { delay(100); }
Serial.print("WiFi connected, IP: ");
Serial.println(WiFi.localIP());
server.begin();
// Set up WebSocket
ws.onEvent(onEvent);
server.addHandler(&ws);
}
void loop() {
ws.cleanupClients();
}
void onEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type, void *arg, uint8_t *data, size_t len) {
switch (type) {
case WS_EVT_CONNECT:
Serial.printf("WebSocket client #%u connected from %s\n", client->id(), client->remoteIP().toString().c_str());
break;
case WS_EVT_DISCONNECT:
Serial.printf("WebSocket client #%u disconnected\n", client->id());
break;
case WS_EVT_DATA:
handleWebSocketMessage(arg, data, len);
break;
case WS_EVT_PONG:
Serial.printf("WebSocket client #%u ponged\n", client->id());
break;
case WS_EVT_ERROR:
Serial.printf("WebSocket client #%u error(%u): %s\n", client->id(), *((uint16_t *)arg), (char *)data);
break;
}
}
void handleWebSocketMessage(void *arg, uint8_t *data, size_t len) {
AwsFrameInfo *info = (AwsFrameInfo *)arg;
if (info->final && info->index == 0 && info->len == len && info->opcode == WS_TEXT) {
data[len] = 0;
String message = (char *)data;
Serial.println(" ");
// Handle WebSocket message
Serial.print("Recieved Message:");
Serial.println(message);
}
}
In the Disconnect part
case WS_EVT_DISCONNECT:
Serial.printf("WebSocket client #%u disconnected\n", client->id());
break;
When a client connect and disconnect it is displayed fine .But when a client disconnects due to power loss or any other reason (couldnt send closing frame to server) .When the device connects again it is treated as second client .So what should i do to disconnect the first client .