khoih-prog / WebSockets2_Generic

A WebSocket Server and Client library for Arduino, based on RFC6455, for writing modern Websockets applications. Now support ESP8266, ESP32 (including ESP32-S2 Saola, AI-Thinker ESP-12K, WT32_ETH01, etc.), nRF52, SAMD21, SAMD51, SAM DUE, STM32F/L/H/G/WB/MP1, Teensy, RP2040-based, etc. boards, with WiFiNINA, Teensy 4.1 NativeEthernet/QNEthernet, Ethernet W5x00 / ENC28J60 / LAN8742A / LAN8720, ESP8266 / ESP32-AT modules/shields, as well as SINRIC / Alexa / Google Home
GNU General Public License v3.0
81 stars 30 forks source link

Connect() is blocking? #45

Closed Oozlum closed 2 years ago

Oozlum commented 2 years ago

Looking at the example code: bool connected = client.connect(websockets_connection_string); it seems to me that connect() will block until the connection is made or fails. Is that correct? Is there any way to perform the connection in the background and use the event callback to detect connection?

khoih-prog commented 2 years ago

Hi @Oozlum

That's true it'll try to connect and exit only after returning either true or false, as written in the example

https://github.com/khoih-prog/WebSockets2_Generic/blob/9f748ee37e072f2e05399c1a8370f1bb974be947/examples/ESP32/Esp32-Client/Esp32-Client.ino#L101-L113

You can turn on debug to display what's wrong with the connection (at which step), such as

#define _WEBSOCKETS_LOGLEVEL_     4

https://github.com/khoih-prog/WebSockets2_Generic/blob/9f748ee37e072f2e05399c1a8370f1bb974be947/src/WebSockets2_Generic_Client.hpp#L592-L707

Examples are just examples to demo the basic functions of the library. You have to modify the example, to use FreeRTOS multi-task or multi-thread to have non-blocking effect, for your special use-case.

As I don't spend time on this library anymore (unless fixing breaking bugs), I suggest you try to post the issue on ArduinoWebsockets library, on which this library is based, or Arduino Forum, to get better help.

Good Luck,