Search code examples
websocketesp8266nodemcu

ESP8266 not connecting to websocket server


I have created and deployed a websocket to the heroku. I am able to use the websocket on postman but I can't connect it with my node mcu. I could connect the node mcu to the wifi but not with the websocket. I am not sure about the port number which should be used for begin() method for websocketsclient object.

Below is my code to connect with my websocket:

#include "ESP8266WiFi.h"
#include "WebSocketsClient.h"

// WiFi parameters to be configured
const char* ssid = "<wifi_ssid>"; // Write here your router's username
const char* password = "<password>"; // Write here your router's passward
int LED_STATUS = 0;
const char* host = "<project_name>.herokuapp.com";
const uint16_t port = 3000;
const char* url = "/";

WebSocketsClient webSocketsClient = WebSocketsClient();

void handleMessage(char * message){
  Serial.println("message...");
  Serial.println(message);
}

void webSocketCallback(WStype_t type, uint8_t * payload, size_t length){
  toggleLED();
  switch(type){
    case WStype_DISCONNECTED:
      offLED();
      break;
    case WStype_TEXT:
      onLED();
      handleMessage((char*) payload);
      break;
    case WStype_CONNECTED:
    default:
      onLED();
      break;
  }
}

void toggleLED(){
  LED_STATUS = (LED_STATUS + 1)%2;
  digitalWrite(LED_BUILTIN, LED_STATUS); 
}

void offLED(){
  LED_STATUS = 1;
  digitalWrite(LED_BUILTIN, LED_STATUS); 
}

void onLED(){
  LED_STATUS = 0;
  digitalWrite(LED_BUILTIN, LED_STATUS); 
}

void setup(void)
{ 
  Serial.begin(9600);
  // Connect to WiFi
  WiFi.begin(ssid, password);

  //setting the led pin
  pinMode(LED_BUILTIN, OUTPUT);

  // while wifi not connected yet, print '.'
  // then after it connected, get out of the loop
  while (WiFi.status() != WL_CONNECTED) {
     toggleLED();
     delay(500);
     Serial.print(".");
  }
  //WiFi connected, IP address
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println(WiFi.localIP());

  offLED();

  //websocket connection
  webSocketsClient.begin(host, port, url);
  webSocketsClient.onEvent(webSocketCallback);

  webSocketsClient.setReconnectInterval(5000);
  
}

void loop() {
  // Nothing

  webSocketsClient.loop();
}

Solution

  • Solutions(few mistakes in the code):

    1. Since my websocket supports secured connection : wss, so instead of begin() need to use beginSSL()
    2. since wss is used, port number for secured connections is 443