Can we use WiFiServer to accept connections in blocking mode?
Posted: Sun Jul 14, 2024 10:18 am
In unix we would typically code a server using something like:
The call to accept() blocks until a connection is received, at which point it springs back into life and returns a socket we can use for communicating with the client. The equivalent when coding for an ESP32 seems to be something like:
This works fine, but the call to server.available() is non-blocking so the loop is running continuously and using 100% CPU. On unix calling accept() would suspend the thread until data was available, which is good because it's pretty antisocial to consume 100% CPU on a multitasking OS.
My question is whether there is a way to make server.available() behave like the sockets accept() function and block until a connection is available?
I realise that a microcontroller is very different from the sort of computer we'd typically use to run unix, and keeping a thread spinning may simply not be an issue. However if I want to create a new task to handle the client (using vTaskCreate()) then keeping the main thread spinning will be taking CPU away from the new task(s). It seems more elegant so have the available() function block.
I realise that I can just use the same sockets API that is used on unix, and in fact I have this working nicely on my ESP32-WROOM-32. However the sockets API is not especially entertaining to code for and the WiFiServer and WiFiClient provided in WiFi.h are much nicer to use.
Code: Select all
listen(sock_srv, 1);
while (true) {
sockaddr addr_client;
int sock_client = accept(sock_srv, &addr_client, NULL);
Code: Select all
// Listen on port 23
WiFiServer server(23);
server.begin();
// Loop to handle connections
while (true) {
// Wait for a connection
WiFiClient client = server.available();
if (client) {
...
My question is whether there is a way to make server.available() behave like the sockets accept() function and block until a connection is available?
I realise that a microcontroller is very different from the sort of computer we'd typically use to run unix, and keeping a thread spinning may simply not be an issue. However if I want to create a new task to handle the client (using vTaskCreate()) then keeping the main thread spinning will be taking CPU away from the new task(s). It seems more elegant so have the available() function block.
I realise that I can just use the same sockets API that is used on unix, and in fact I have this working nicely on my ESP32-WROOM-32. However the sockets API is not especially entertaining to code for and the WiFiServer and WiFiClient provided in WiFi.h are much nicer to use.