Guys i want to send data from my esp32 to node js server but disconnected message appear the port and hostname are correct.i reach server from react

// Wifi configuration
#include <WiFi.h>
#include <WiFiMulti.h>
#include <WiFiClientSecure.h>
WiFiMulti WiFiMulti;
WiFiClient client;
// SocketIO configuration
#include <WebSocketsClient.h>
#include <SocketIOclient.h>
char host[] = "192.168.8.100"; // SocketIO Server Address
int port =3000; // SocketIO Port Address
SocketIOclient socketIO;
#include <ArduinoJson.h>
unsigned long previousMillis = 0;
unsigned long currentMillis;
unsigned long interval=1000; //interval for sending data to the websocket server in ms
void setup() {

Serial.begin(9600);
Serial.setDebugOutput(true);

WiFiMulti.addAP("", "");
//WiFi.disconnect();
while(WiFiMulti.run() != WL_CONNECTED) {
    delay(100);
}
String ip = WiFi.localIP().toString();
Serial.printf("[SETUP] WiFi Connected %s\n", ip.c_str());

// server address, port and URL
socketIO.begin(host, port);

// event handler
socketIO.onEvent(socketIOEvent);

}

void loop() {
socketIO.loop();
currentMillis=millis();
// Send data each second
if (abs((long)(currentMillis - previousMillis)) >= interval) {
previousMillis = currentMillis;

  // creat JSON message for Socket.IO (event)
    DynamicJsonDocument doc(1024);
    JsonArray array = doc.to<JsonArray>();
    
    // add evnet name
    // Hint: socket.on('event_name', ....
    array.add("message");

    // add payload (parameters) for the event
    JsonObject param1 = array.createNestedObject();
    // JSON to String (serializion)
    String output;
    serializeJson(doc, output);

    // Send event        
    socketIO.sendEVENT(output);

    // Print JSON for debugging
    Serial.println("bdfhgdjhgjhgsdjfgjsd" + output);

}

}

void hexdump(const void mem, uint32_t len, uint8_t cols = 16) {
const uint8_t
src = (const uint8_t*) mem;
Serial.printf("\n[HEXDUMP] Address: 0x%08X len: 0x%X (%d)", (ptrdiff_t)src, len, len);
for(uint32_t i = 0; i < len; i++) {
if(i % cols == 0) {
Serial.printf("\n[0x%08X] 0x%08X: ", (ptrdiff_t)src, i);
}
Serial.printf("%02X ", *src);
src++;
}
Serial.printf("\n");
}

void socketIOEvent(socketIOmessageType_t type, uint8_t * payload, size_t length) {
switch(type) {
case sIOtype_DISCONNECT:
//
Serial.printf("[IOc] Disconnected!\n");
break;
case sIOtype_CONNECT:
Serial.printf("[IOc] Connected to url: %s\n", payload);

        // join default namespace (no auto join in Socket.IO V3)
        socketIO.send(sIOtype_CONNECT, "/");
        break;
    case sIOtype_EVENT:
        Serial.printf("[IOc] get event: %s\n", payload);
        break;
    case sIOtype_ACK:
        Serial.printf("[IOc] get ack: %u\n", length);
        hexdump(payload, length);
        break;
    case sIOtype_ERROR:
        Serial.printf("[IOc] get error: %u\n", length);
        hexdump(payload, length);
        break;
    case sIOtype_BINARY_EVENT:
        Serial.printf("[IOc] get binary: %u\n", length);
        hexdump(payload, length);
        break;
    case sIOtype_BINARY_ACK:
        Serial.printf("[IOc] get binary ack: %u\n", length);
        hexdump(payload, length);
        break;
}

}

the version of socket io in node js: 4.8.1 and in esp32 is : 0.3.0

i get this message in Serial monitor:

.Connected to WiFi
Ping succeeded!
Disconnected from server!

this is my code :

#include <SocketIOclient.h>

SocketIOclient webSocket;

// Replace with your network credentials
const char* ssid = "....";
const char* password = "...";

// Server IP
const char* serverIP = "192.168.8.100"; // Your server IP
const int port = 3000;

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

while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");  // Print a dot while connecting
    delay(2000);
}
Serial.println("Connected to WiFi");

// Now ping the server
if (pingServer(serverIP)) {
    Serial.println("Ping succeeded!");
    // Start the WebSocket connection
    webSocket.begin(serverIP, port);
    webSocket.onEvent(webSocketEvent);
} else {
    Serial.println("Ping failed.");
}
delay(3000);

}

void loop() {
webSocket.loop(); // Keep the WebSocket connection alive
}

void webSocketEvent(socketIOmessageType_t type, uint8_t* payload, size_t length) {
if (type == sIOtype_CONNECT) {
Serial.println("Connected to server!");
} else if (type == sIOtype_DISCONNECT) {
Serial.println("Disconnected from server!");
} else if (type == sIOtype_EVENT) {
Serial.printf("Received event: %s\n", payload);
} else if (type == sIOtype_ACK) {
Serial.println("Acknowledgment received!");
}
}

bool pingServer(const char* server) {
WiFiClient client;
bool result = client.connect(server, port);
client.stop(); // Close the connection
return result;
}

is the port open on computers firewall?

i solve the problem i can coonect to socket IO server but the problem ESP32 SocketIO connects an disconnects repeatedly i get this:
Connected to WiFi
Ping succeeded!
Connected to server!
Disconnected from server!
Connected to server!
Disconnected from server!
Connected to server!
Disconnected from server!
Connected to server!
Disconnected from server!
Connected to server!
Disconnected from server!
Connected to server!

i want to connect esp32 to node js server voia socketIo but the problem esp32 connect and disconnect

version of engine.io server: 3.5.0 , socket io server: 4.8.1 , client socketIo (esp32): 0.3.0

this is code for esp32:

#include <SocketIOclient.h>

SocketIOclient webSocket;

// Replace with your network credentials  
const char* ssid = ".....";
const char* password = "...";

// Server IP
const char* serverIP = "192.168.8.14"; // Your server IP
const int port = 3000;

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

    while (WiFi.status() != WL_CONNECTED) {
        Serial.print(".");  // Print a dot while connecting
        delay(2000);
    }
    Serial.println("Connected to WiFi");

    // Now ping the server
    if (pingServer(serverIP)) {
        Serial.println("Ping succeeded!");
        // Start the WebSocket connection
        webSocket.begin(serverIP, port,"/socket.io/?EIO=4");
        webSocket.onEvent(webSocketEvent);
    } else {
        Serial.println("Ping failed.");
    }
    delay(3000);
}   

void loop() {
    webSocket.loop();  // Keep the WebSocket connection alive

}

void webSocketEvent(socketIOmessageType_t type, uint8_t* payload, size_t length) {
    if (type == sIOtype_CONNECT) {
        Serial.println("Connected to server!");
    } else if (type == sIOtype_DISCONNECT) {
        Serial.println("Disconnected from server!");
    } else if (type == sIOtype_EVENT) {
        Serial.printf("Received event: %s\n", payload);
    } else if (type == sIOtype_ACK) {
        Serial.println("Acknowledgment received!");
    }
}

bool pingServer(const char* server) {
    WiFiClient client;
    bool result = client.connect(server, port);
    client.stop();  // Close the connection
    return result;                                    
}

and this is the code for node js:

const { createServer } = require('http');
const { Server } = require('socket.io');

// Create an HTTP server
const httpServer = createServer();

// Initialize Socket.IO server
const socket = new Server(httpServer, {
    cors:{
        origin:'*',
        credentials: true
    },
});

// Listen for incoming socket connections
socket.on('connection', (sock) => {
    console.log("new client connected");
    sock.on('message',(data)=>{
        console.log(data);
    });
})
// Start the server
httpServer.listen(3000, () => {
    console.log('The server is running on port 3000');
});


i try to downgrade and upgrade version but i stilll in the same problem

I know nothing about socket io, however I would suggest that the first step is to put the ESP32 to one side and check to see if a Node.js client running on the same machine as the Node.js server works OK. Next check for firewall issues by doing the same test with the client and server running on different machines.

If these tests are successful then use Wireshark to log the interaction between the client and server, then do the same with the ESP32 connecting to the server. That may give you some indication of what's happening.

i'm not familiar with wireshark but i will show you what i see in the debuger of the server:

socket.io:client no namespace joined yet, close the client +46s
socket.io:client forcing transport close +1ms
socket.io:client client close with reason forced close +1ms
socket.io:client client close with reason forced server close +2ms
engine intercepting request for path "/socket.io/" +46s
engine handling "GET" http request "/socket.io/?EIO=4&transport=polling" +1ms
engine applying middleware n°1 +0ms
engine handshaking client "8Ex9MMrgZ37l7LEgAAAf" +1ms
socket.io:server incoming connection with id 8Ex9MMrgZ37l7LEgAAAf +46s
engine applying middleware n°1 +52ms
engine writing headers: {"Access-Control-Allow-Origin":"*","Access-Control-Allow-Credentials":"true"} +1ms
engine upgrading existing transport +2ms

i want to connect esp32 to node js server voia socketIo but the problem esp32 connect and disconnect

version of engine.io server: 3.5.0 , socket io server: 4.8.1 , client socketIo (esp32): 0.3.0

this is code for esp32:

#include <SocketIOclient.h>

SocketIOclient webSocket;

// Replace with your network credentials
const char* ssid = ".....";
const char* password = "...";

// Server IP
const char* serverIP = "192.168.8.14"; // Your server IP
const int port = 3000;

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

while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");  // Print a dot while connecting
    delay(2000);
}
Serial.println("Connected to WiFi");

// Now ping the server
if (pingServer(serverIP)) {
    Serial.println("Ping succeeded!");
    // Start the WebSocket connection
    webSocket.begin(serverIP, port,"/socket.io/?EIO=4");
    webSocket.onEvent(webSocketEvent);
} else {
    Serial.println("Ping failed.");
}
delay(3000);

}

void loop() {
webSocket.loop(); // Keep the WebSocket connection alive

}

void webSocketEvent(socketIOmessageType_t type, uint8_t* payload, size_t length) {
if (type == sIOtype_CONNECT) {
Serial.println("Connected to server!");
} else if (type == sIOtype_DISCONNECT) {
Serial.println("Disconnected from server!");
} else if (type == sIOtype_EVENT) {
Serial.printf("Received event: %s\n", payload);
} else if (type == sIOtype_ACK) {
Serial.println("Acknowledgment received!");
}
}

bool pingServer(const char* server) {
WiFiClient client;
bool result = client.connect(server, port);
client.stop(); // Close the connection
return result;
}

and this is the code for node js:

const { createServer } = require('http');
const { Server } = require('socket.io');

// Create an HTTP server
const httpServer = createServer();

// Initialize Socket.IO server
const socket = new Server(httpServer, {
cors:{
origin:'*',
credentials: true
},
});

// Listen for incoming socket connections
socket.on('connection', (sock) => {
console.log("new client connected");
sock.on('message',(data)=>{
console.log(data);
});
})
// Start the server
httpServer.listen(3000, () => {
console.log('The server is running on port 3000');
});

the debugger of my server show me this:
socket.io:client no namespace joined yet, close the client +46s
socket.io:client forcing transport close +1ms
socket.io:client client close with reason forced close +2ms
socket.io:client client close with reason forced server close +0ms
engine intercepting request for path "/socket.io/" +46s
engine handling "GET" http request "/socket.io/?EIO=4&transport=polling" +2ms
engine applying middleware n°1 +3ms
engine handshaking client "vhbcg4P3M5Y21xz0AAAR" +4ms
socket.io:server incoming connection with id vhbcg4P3M5Y21xz0AAAR +46s
engine applying middleware n°1 +21ms
engine writing headers: {"Access-Control-Allow-Origin":"*","Access-Control-Allow-Credentials":"true"} +4ms
engine upgrading existing transport +4ms

Please edit your post, select all code and click the

< CODE/ >

button; next save your post. This will make the code easier to read, easier to copy and the forum software will display it correctly.

I have merged your cross-posts @ma_20assou.

Cross-posting is against the Arduino forum rules. The reason is that duplicate posts can waste the time of the people trying to help. Someone might spend a lot of time investigating and writing a detailed answer on one topic, without knowing that someone else already did the same in the other topic.

Repeated cross-posting can result in a suspension from the forum.

In the future, please only create one topic for each distinct subject matter. This is basic forum etiquette, as explained in the "How to get the best out of this forum" guide. It contains a lot of other useful information. Please read it.

Thanks in advance for your cooperation.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.