gilmaimon / ArduinoWebsockets

A library for writing modern websockets applications with Arduino (ESP8266 and ESP32)
GNU General Public License v3.0
482 stars 97 forks source link

[Resolved] How to make "auto client = WSserver.accept();" non blocking #110

Closed happytm closed 3 years ago

happytm commented 3 years ago

I am trying to use your server library but having problem with loop section which seems to block the call to a function processData() in my code. I read through wiki pages but could not figure it out.

Is there any way around it?

My loop looks like below:

void loop() {
 if (triggerProcessData == 1) { 
    processData(); 
    triggerProcessData = 0; 
    } 

  auto client = WSserver.accept();
  client.onMessage(handle_message);
  processData();

  while (client.available()) {
  client.poll();
  }
} // End of loop

Thanks.

gilmaimon commented 3 years ago

Look at this wiki page

You can do server.poll(), it will return either true/false indicating if there is a client waiting to connect :)

happytm commented 3 years ago

Thank you for your prompt reply. I ended up using advanced echo server adapting to my use case and it works fine.

Here is my loop code:

void loop() {

#if WEBSOCKETS
 while (WSserver.available()) {
    // if there is a client that wants to connect
    if(WSserver.poll()) {
      //accept the connection and register callback
      Serial.println("Accepting a new client!");
      WebsocketsClient client = WSserver.accept();
      client.onMessage(onMessage);

      // store it for later use
      allClients.push_back(client);

      }
      // check for updates in all clients
      pollAllClients();

      if (triggerProcessData == 1) { 
      processData(); 
      triggerProcessData = 0; 
      } 

       #if MQTT
       broker.loop();  // Don't forget to add loop for every broker and clients
       myClient.loop();
       #endif
       }  
#endif  
} // End of loop

Thanks again.