Unable to connect to websocket

hello
i try to connect esp32 module to my server via websocket
in server code i defined port 3000 to listen by server
i try different way but no success.
can any body help to me
server address: https://ehome.iran.liara.run

my code:

#include <Arduino.h>
#include <WebSocketsClient.h>
#include <WiFi.h>
#include <WiFiMulti.h>
#include <ESP32Ping.h>

WiFiMulti objWifiMulti;
WebSocketsClient objWebSocketClient;

void setup()
{
  // put your setup code here, to run once:
  Serial.begin(115200);
  Serial.println("\n\nBooting; please wait...");
  delay(2000);

  pinMode(2, OUTPUT);
  objWifiMulti.addAP("***", "***");

  Serial.print("\n\nBoot complete; connecting to wifi network.");

  while (objWifiMulti.run() != WL_CONNECTED)
  {
    Serial.print(".");
    digitalWrite(2, !digitalRead(2));
    delay(1000);
  }

  Serial.println("\nconnecting to WIFI network successful; assign ip is: " + WiFi.localIP().toString());

  digitalWrite(2, HIGH);

  //objWebSocketClient.begin("ws://192.168.25.24",3000);
  //objWebSocketClient.beginSSL("ehome.iran.liara.run",443,"","","wss" );
  objWebSocketClient.begin("ehome.iran.liara.run",80,"","ws");
  
  // objWebSocketClient.beginSocketIO("ehome.iran.liara.run", 3000, "", "wss");
}

void loop()
{
  Ping.ping("8.8.8.8");
  Serial.print("ping IP 8.8.8.8 in ");
  Serial.print(Ping.averageTime());
  Serial.println(" ms.");
  delay(1000);
  // put your main code here, to run repeatedly:
  objWebSocketClient.loop();
  objWebSocketClient.sendTXT("test");
}

my server code

const express = require("express");
const app = express();
const http = require("http");
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);


app.use(express.static(__dirname + "/public"));

app.get("/", (req, res) => {
    //res.send({ username: "require", password: "require" });
    res.sendFile(__dirname + "/public/assets/index.html");
});

io.on("connection", (socket) => {
    console.log("\nconnection to new Client Stablished by ID: " + socket.id);

    socket.on("req_status", (part) => {
        console.log("Request status of " + part);

        socket.emit("send_status", part, "on");

    });

    socket.on("disconnect", () => {
        console.log("\nconnection lost from client with ID: " + socket.id);
    });
});


server.listen(3000, () => {
    console.log("Server successfuly running on port 3000.\n\nwaiting for clients...");
});

Your code should prints a multiple diagnostic messages. Do you see it in the console?
Please insert sketch output to the forum (as text with code tags).

1 Like

entr^���00805e4C�

Booting; please wait...

Boot complete; connecting to wifi network.
connecting to WIFI network successful; assign ip is: 192.168.25.14
ping IP 8.8.8.8 in 140.52 ms.
ping IP 8.8.8.8 in 137.69 ms.
ping IP 8.8.8.8 in 113.63 ms.
ping IP 8.8.8.8 in 153.82 ms.
ping IP 8.8.8.8 in 120.29 ms.
ping IP 8.8.8.8 in 152.69 ms.
ping IP 8.8.8.8 in 121.92 ms.
ping IP 8.8.8.8 in 76.91 ms.
ping IP 8.8.8.8 in 114.25 ms.

this is all thing that i seen from serial monitor

And how you considered that it doesn't connect to the socket? You haven't any diagnostic messages regarding this

1 Like

i add my server side code
when new client came, server log it and i can see it

Is the host ehome.iran.liara.run reachable from your network? As far I see, you use non-public IP 192.168.x.x for your board. Do you setup a gateway?

1 Like

yes. server located on internet and i can open it via any browser on any network that access to internet

Are you sure about your server script?

Try to connect with a websocket client using yout PC.
If i remember, should be exist an add-on for Chrome.

I've tried with this, but I can't reach your websocket server.

1 Like

hi
after test my server with websocket tester I'm not sure about my server side code :confused:

do you have any example for this situation

as I check and found, all guide learn to run Web server on arduino device, not in real host and server...
and I need to run my server code in Web....

websocket | Random Nerd Tutorials

1 Like

thanks
but in link that you sent web server run in esp32 or esp8266 not run a server on internet

I need an article that talk about run Web server on internet...

Try your script on a PC with node.js and once you are sure it is good and works at least in a local network, try to upload it to the server.

1 Like

This is another point to check.
Are you sure your hosting service is able to run JavaScript from server side?

I've assumed yes, because the page seems working well, but maybe it was served from a web service like Apache or something like this and not from your script.

1 Like

hello again
i update my server code and it work fine(i test it with Socket.IO Test Client chrome extension and connection successfully established)
my site address

but i still cant connect to server via my esp32 device and get the flowing error in serial monitor

[311164][E][WiFiClient.cpp:313] setSocketOption(): fail on -1, errno: 9, "Bad file number"

and this is my esp32 code
#include <Arduino.h>
#include <WebSocketsClient.h>
#include <WiFi.h>
#include <WiFiMulti.h>
#include <ESP32Ping.h>

WiFiMulti objWifiMulti;
WebSocketsClient objWebSocketClient;

void setup()
{
  // put your setup code here, to run once:
  Serial.begin(115200);
  Serial.println("\n\nBooting; please wait...");
  delay(2000);

  pinMode(2, OUTPUT);
  objWifiMulti.addAP("***", "***");

  Serial.print("\n\nBoot complete; connecting to wifi network.");

  while (objWifiMulti.run() != WL_CONNECTED)
  {
    Serial.print(".");
    digitalWrite(2, !digitalRead(2));
    delay(1000);
  }

  Serial.println("\nconnecting to WIFI network successful; assign ip is: " + WiFi.localIP().toString());

  digitalWrite(2, HIGH);

  // objWebSocketClient.begin("ws://192.168.25.24",3000);
  objWebSocketClient.beginSSL("ehome.iran.liara.run",443,"/","","WSS" );
  //objWebSocketClient.begin("ehome.iran.liara.run",443,"","wss");
  //objWebSocketClient.beginSocketIOSSL("ehome.iran.liara.run", 443, "/","wss");

  // objWebSocketClient.beginSocketIO("ehome.iran.liara.run", 3000, "", "wss");
}

void loop()
{
  Ping.ping("8.8.8.8");
  Serial.print("ping IP 8.8.8.8 in ");
  Serial.print(Ping.averageTime());
  Serial.println(" ms.");
  delay(1000);
  // put your main code here, to run repeatedly:
  objWebSocketClient.loop();
  objWebSocketClient.sendTXT("test");
}

can anybody help me :sleepy:

hello
finally a completely change the server side(node.js) code with web-socket and successfully connect to it via my esp32.

my esp 32 module now can connect to server but immediately disconnect and this loop happened again
this is the error of my serial monitor that shown

ping IP 8.8.8.8 in 80.41 ms.
[2715728][E][WiFiClient.cpp:313] setSocketOption(): fail on -1, errno: 9, "Bad file number"
ping IP 8.8.8.8 in 88.71 ms.
ping IP 8.8.8.8 in 113.31 ms.
[2728606][E][WiFiClient.cpp:313] setSocketOption(): fail on -1, errno: 9, "Bad file number"
ping IP 8.8.8.8 in 104.36 ms.
ping IP 8.8.8.8 in 108.73 ms.
[2741525][E][WiFiClient.cpp:313] setSocketOption(): fail on -1, errno: 9, "Bad file number"

*** i solve this error according to bellow tutorial; but system still immediately connect and disconnect :sleepy:
tutorial Link

and this is my Arduino(esp32) code

#include <Arduino.h>
#include <WiFi.h>
#include <WiFiMulti.h>

#include <WebSocketsClient.h>
#include <ESP32Ping.h>

WiFiMulti objWifiMulti;
WebSocketsClient objWebSocketClient;


void setup()
{
  // put your setup code here, to run once:
  Serial.begin(115200);
  Serial.println("\n\nBooting; please wait...");
  delay(2000);

  pinMode(2, OUTPUT);
  objWifiMulti.addAP("***", "***");

  Serial.print("\n\nBoot complete; connecting to wifi network.");

  while (objWifiMulti.run() != WL_CONNECTED)
  {
    Serial.print(".");
    digitalWrite(2, !digitalRead(2));
    delay(1000);
  }
  Serial.println("\nconnecting to WIFI network successful; assign ip is: " + WiFi.localIP().toString());

  digitalWrite(2, HIGH);

  objWebSocketClient.beginSSL("ehome.iran.liara.run",443,"/","","wss");
  //objWebSocketClient.onEvent(webSocketEvent);
  //objWebSocketClient.sendTXT("Hello FROM ESP32!");
  //objWebSocketClient.begin("ehome.iran.liara.run", 443, "/", "wss");
}

void loop()
{
  // put your main code here, to run repeatedly:
  Ping.ping("8.8.8.8");
  Serial.print("ping IP 8.8.8.8 in ");
  Serial.print(Ping.averageTime());
  Serial.println(" ms.");
  delay(1000);
  objWebSocketClient.sendTXT("Hello FROM ESP32!");
  objWebSocketClient.loop();
}

and also i get this warning on compiling time

Compiling .pio\build\esp32dev\libd94\ESP32Ping\ping.cpp.o
Compiling .pio\build\esp32dev\FrameworkArduino\Esp.cpp.o
.pio/libdeps/esp32dev/WebSockets/src/WebSocketsServer.cpp: In member function 'WSclient_t* WebSocketsServerCore::handleNewClient(WiFiClient*)':
.pio/libdeps/esp32dev/WebSockets/src/WebSocketsServer.cpp:634:12: warning: function may return address of local variable [-Wreturn-local-addr]
return client;
^~~~~~
.pio/libdeps/esp32dev/WebSockets/src/WebSocketsServer.cpp:626:20: note: declared here
WSclient_t dummy = WSclient_t();
^~~~~
Archiving .pio\build\esp32dev\lib273\libWebSockets.a
Compiling .pio\build\esp32dev\FrameworkArduino\FirmwareMSC.cpp.o

can anybody help me

@hamiid,

Your two topics on the same or similar subject have been merged.

Please do not duplicate your questions as doing so wastes the time and effort of the volunteers trying to help you as they are then answering the same thing in different places.

Please create one topic only for your question and choose the forum category carefully. If you have multiple questions about the same project then please ask your questions in the one topic as the answers to one question provide useful context for the others, and also you won’t have to keep explaining your project repeatedly.

Repeated duplicate posting could result in a temporary or permanent ban from the forum.

Could you take a few moments to Learn How To Use The Forum

It will help you get the best out of the forum in the future.

Thank you.

1 Like

What if you change Ping.ping("...."); in the real adress of the server?

it's not important
I use ping to be sure Internet is connected

and I also test server with websocket client tool and sure it work fine

Hi hamiid, do you still with the same problem? I have the same problem for many days and I can´t solved.

hi alexfdz

fourthly I solve the problem, thanks to Google and chatgpt

if you remove delay on loop the disconnect error solve
also you must setup enableheartbit on WebSocketsClient

and this is the sample code that chatgpt generated

#include <WiFi.h>
#include <WebSocketsClient.h>

const char* ssid = "your_wifi_name";
const char* password = "your_wifi_password";

WebSocketsClient webSocket;

void setup() {
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  Serial.println("Connected to WiFi");

  webSocket.begin("ws://your_server_domain_or_ip:80");  // replace with your server's domain or IP address, and the port number
  webSocket.onEvent(webSocketEvent);
  webSocket.setReconnectInterval(5000);
  webSocket.enableHeartbeat(1000, 1000, 2);
}

void loop() {
  webSocket.loop();
}

void webSocketEvent(WStype_t type, uint8_t * payload, size_t length) {
  switch(type) {
    case WStype_DISCONNECTED:
      Serial.println("Disconnected!");
      break;
    case WStype_CONNECTED:
      Serial.println("Connected to server!");
      break;
    case WStype_TEXT:
      Serial.println("Received text: ");
      Serial.println((char*)payload);
      break;
  }
}