Search code examples
arduinoesp8266nodemcu

Unable to access a websocket using ESP8266 (Using Arduino IDE)


I been trying to get my ESP8266 to connect to a websocket, but no luck so far. Things that are ruled out are:

  1. The ESP8266 is connected to WiFi and has access to Internet (checked using a HTTP request).
  2. Not a problem with the socket server, I spun up my own websocket server and it was not hit.
  3. Tried port 80 and 443.

My code is as follows, keeps printing

Not Connected!

:

#include <Arduino.h>
#include "WebSocketClient.h"
#include "ESP8266WiFi.h"
    
WebSocketClient ws(true);
    
void setup() {
  Serial.begin(115200);
  WiFi.begin("SSID", "PASSWORD");
    
  Serial.print("Connecting");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
}
    
void loop() {
  if (!ws.isConnected()) {
    ws.connect("echo.websocket.org", "/", 80);
    Serial.println("Not connected!");
  } else {
    ws.send("hello");
    
    String msg;
    if (ws.getMessage(msg)) {
      Serial.println(msg);
    }
  }
  delay(500);
}

Solution

  • WebSocketClient ws(true); tries to connect securely and uses WiFiClientSecure in stead of WiFiClient. This will probably require specifying a certificate or some such.

    Try WebSocketClient ws(false); to see if that works (tries to force an insecure connection).