ESP32 wifi server with multiple clients

IngLCT
Posts: 1
Joined: Tue Aug 23, 2022 3:44 pm

ESP32 wifi server with multiple clients

Postby IngLCT » Tue Sep 13, 2022 7:24 pm

Hello everyone

I have a program where I configure my ESP32 as a server and it sent randomly generated data, the problem is that I can only connect 1 client at a time, what I want is that multiple clients can connect and they all receive the same information,

I put the code that I have in my ESP32 as a server

Code: Select all

#include <WiFi.h>
 
const char* ssid = "SSID";
const char* password =  "Password";

char data[9];
 
WiFiServer wifiServer(80);
 
void setup() {
 
  Serial.begin(115200);
 
  delay(1000);
 
  WiFi.begin(ssid, password);
 
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Conectando a WiFi..");
  }
 
  Serial.println("Conectado a la red WiFi network");
  Serial.println(WiFi.localIP());

 
  wifiServer.begin();
}
 
void loop() {
 
  WiFiClient client = wifiServer.available();
 
  if (client) {
 
    while(client.connected()) {
      //Serial.println("Client Connected");
    
        data[0] = random(30,50);
        data[1] = random(30,50);
        data[2] = random(30,50);
        data[3] = random(30,50);
        data[4] = random(30,50);
        data[5] = random(30,50);
        data[6] = random(30,50);
        data[7] = random(30,50);
        data[8] = random(30,50);
        
        client.write(data,9);
        Serial.println(int(data[0]));
        Serial.println(int(data[1]));
        Serial.println(int(data[2]));
        Serial.println(int(data[3]));
        Serial.println(int(data[4]));
        Serial.println(int(data[5]));
        Serial.println(int(data[6]));
        Serial.println(int(data[7]));
        Serial.println(int(data[8]));
        delay(1000);
    } 
  }
}
I am managing the clients with python
the client code is as follows

Code: Select all

import socket           
 
sock = socket.socket()
 
host = "192.168.1.68" #ESP32 IP in local network
port = 80             #ESP32 Server Port    
 
sock.connect((host, port))

data = ""
lista = [0,0,0,0,0,0,0,0,0]
x = 0

while True:
    
    data = sock.recv(1)
    #x = data.decode()
    #y = x.split("p")
    buffer = int.from_bytes(data,"big")
    lista[x] = buffer
    x = x + 1
    if x >=9:
        print(lista)
        x=0
the idea is that all clients have the same code and receive the same data
but it only allows me to connect 1 client at a time


haddow777
Posts: 14
Joined: Tue Jul 13, 2021 3:25 pm

Re: ESP32 wifi server with multiple clients

Postby haddow777 » Sun Jan 29, 2023 7:38 am

I just ran into this problem myself. The problem seems to be that the ESP32 version of WiFiClient and WiFiServer differ from the Arduino version. Here's what it says about WiFiServer.available():
Gets a client that is connected to the server and has data available for reading. The connection persists when the returned client object goes out of scope; you can close it by calling client.stop().
Note that when whatever variable you store the client socket in goes out of scope, the client gets destroyed. Now the connection is supposed to persist with the server. Yet, when you look at the code of WiFiClient.cpp

Code: Select all

class WiFiClientSocketHandle {
private:
    int sockfd;

public:
    WiFiClientSocketHandle(int fd):sockfd(fd)
    {
    }

    ~WiFiClientSocketHandle()
    {
        close(sockfd);
    }

    int fd()
    {
        return sockfd;
    }
};

WiFiClient::WiFiClient():_connected(false),_timeout(WIFI_CLIENT_DEF_CONN_TIMEOUT_MS),next(NULL)
{
}

WiFiClient::WiFiClient(int fd):_connected(true),_timeout(WIFI_CLIENT_DEF_CONN_TIMEOUT_MS),next(NULL)
{
    clientSocketHandle.reset(new WiFiClientSocketHandle(fd));
    _rxBuffer.reset(new WiFiClientRxBuffer(fd));
}

WiFiClient::~WiFiClient()
{
    stop();
}

WiFiClient & WiFiClient::operator=(const WiFiClient &other)
{
    stop();
    clientSocketHandle = other.clientSocketHandle;
    _rxBuffer = other._rxBuffer;
    _connected = other._connected;
    return *this;
}

void WiFiClient::stop()
{
    clientSocketHandle = NULL;
    _rxBuffer = NULL;
    _connected = false;
}
Notice that when the WiFiServer's available() method is called and it returns a client, it does so using the second constructor when it gives it the int fd value. This gives it the attachment to the internal socket, as far as I can tell. It appears that WiFiClient and WiFiServer are just wrappers for an underlying C library. In any event, when your WiFiClient variable client goes out of scope at the end of the loop function, it gets destroyed, which means it's destructor gets called ~WiFiClient. Now, as you can clearly see in the destructor, it calls stop(). This gets rid of the clientSocketHandle, which calls its destructor, which then in turn calls close(sockfd).

This apparently closes the underlying socket as well, which breaks with what Arduino claims will happen. So first of all, you have to use a variable that will not go out of scope before you want to close the connection. Also, be very aware of operator=. Even if you use a global variable, the next connection the server gets, it will assign that to the client variable, which will run the operator= method, which will in turn call the stop() method as well and kill the connection that was stored in it. So, you will need to manage a list of connections, one for each one, in variables that will not go out of scope or be overwritten.

To cut down on the pain this may cause, you may find this example helpful. It stores all new connections into an array and constantly checks each one to see if any have been disconnected and removes them. it even handles max connection functionality so you don't have to worry if too many clients try to connect at once.

ullixesp
Posts: 83
Joined: Wed Oct 16, 2019 9:34 am
Location: Germany

Re: ESP32 wifi server with multiple clients

Postby ullixesp » Sun Jan 29, 2023 2:07 pm

Ignore what you have done so far and use @Ibernstone's advice and use the ASYNC server.
At some point you'll need it anyway, why not start right away?

Who is online

Users browsing this forum: No registered users and 53 guests