The esp8266 freezes when losing connection with the client
Posted: Thu Apr 07, 2022 9:48 am
With an esp8266 I am trying to implement a simple TPC server to be able to communicate with another esp8266 as a client, initially the communication works, but I have two problems:
1.- How can I get the value of a flag that tells me if a client is connected or has been disconnected
2.- As I said at the beginning, the communication runs ok, but if I de-energize it on the client side, the server freezes and no longer receives any data, I have to restart the server to run again, this is not acceptable
Here is my server code:
1.- How can I get the value of a flag that tells me if a client is connected or has been disconnected
2.- As I said at the beginning, the communication runs ok, but if I de-energize it on the client side, the server freezes and no longer receives any data, I have to restart the server to run again, this is not acceptable
Here is my server code:
Code: Select all
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#define SERIALBAUD 115200
#define MAXCLIENTS 4
const char* ServerSSID = "**********";
const char* ServerPassword = "*********";
int i;
const int LED_PIN = 2;
unsigned int localPort = 8888;
WiFiServer server(localPort);
WiFiClient serverClients[MAXCLIENTS];
bool flagConexionWiFi;
String bufferStringClienteWIFI = "";
void checkIfServerIsConnectec() {
if (server.hasClient()) { //check if there are any new clients
for (i = 0; i < MAXCLIENTS; i++) {
if (!serverClients[i] && !serverClients[i].connected()) { //find free/disconnected spot
if (serverClients[i])
serverClients[i].stop();
serverClients[i] = server.available();
flagConexionWiFi = true;
Serial.println("[DB] Conectado");
continue;
}
else {
flagConexionWiFi = false;
Serial.println("[DB] Sin Conexion");
}
}
WiFiClient serverClient = server.available();
serverClient.stop();
}
}
void checkDataOfClientWiFi() {
for (i = 0; i < MAXCLIENTS; i++) {
if (serverClients[i] && serverClients[i].connected()) {
if (serverClients[i].available()) {
digitalWrite(LED_PIN, LOW);
while (serverClients[i].available()) {
bufferStringClienteWIFI.concat((char) serverClients[i].read());
}
}
digitalWrite(LED_PIN, HIGH);
}
}
}
void setup() {
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, HIGH);
Serial.begin(SERIALBAUD);
bufferStringClienteWIFI.reserve(100);
bufferStringClienteWIFI = "";
WiFi.disconnect(true);
WiFi.mode(WIFI_AP);
WiFi.softAP(ServerSSID, ServerPassword);
server.begin();
server.setNoDelay(true);
Serial.println(); Serial.println();
Serial.print("ESP ready, Server IP:");
Serial.print(WiFi.softAPIP());
Serial.print(" Port:");
Serial.println(localPort);
}
void loop() {
checkIfServerIsConnectec();
checkDataOfClientWiFi();
digitalWrite(LED_PIN, HIGH);
if (bufferStringClienteWIFI != NULL) {
Serial.print(bufferStringClienteWIFI);
bufferStringClienteWIFI = "";
}
delay(1000);
}