arduinoWebSockets icon indicating copy to clipboard operation
arduinoWebSockets copied to clipboard

SocketIOClient for esp8266 doesn't connect to Server Nodejs

Open phungvanquy opened this issue 3 years ago • 1 comments

This is my code for esp8266 : `#include <Arduino.h> #include <ESP8266WiFi.h> #include <ESP8266WiFiMulti.h> #include <ArduinoJson.h>

#include <WebSocketsClient.h> #include <SocketIOclient.h>

#include <Hash.h>

ESP8266WiFiMulti WiFiMulti; SocketIOclient socketIO;

#define USE_SERIAL Serial

void socketIOEvent(socketIOmessageType_t type, uint8_t * payload, size_t length) { switch(type) { case sIOtype_DISCONNECT: USE_SERIAL.printf("[IOc] Disconnected!\n"); break; case sIOtype_CONNECT: USE_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:
    {
        char * sptr = NULL;
        int id = strtol((char *)payload, &sptr, 10);
        USE_SERIAL.printf("[IOc] get event: %s id: %d\n", payload, id);
        if(id) {
            payload = (uint8_t *)sptr;
        }
        DynamicJsonDocument doc(1024);
        DeserializationError error = deserializeJson(doc, payload, length);
        if(error) {
            USE_SERIAL.print(F("deserializeJson() failed: "));
            USE_SERIAL.println(error.c_str());
            return;
        }

        String eventName = doc[0];
        USE_SERIAL.printf("[IOc] event name: %s\n", eventName.c_str());

        // Message Includes a ID for a ACK (callback)
        if(id) {
            // creat JSON message for Socket.IO (ack)
            DynamicJsonDocument docOut(1024);
            JsonArray array = docOut.to<JsonArray>();

            // add payload (parameters) for the ack (callback function)
            JsonObject param1 = array.createNestedObject();
            param1["now"] = millis();

            // JSON to String (serializion)
            String output;
            output += id;
            serializeJson(docOut, output);

            // Send event
            socketIO.send(sIOtype_ACK, output);
        }
    }
        break;
    case sIOtype_ACK:
        USE_SERIAL.printf("[IOc] get ack: %u\n", length);
        hexdump(payload, length);
        break;
    case sIOtype_ERROR:
        USE_SERIAL.printf("[IOc] get error: %u\n", length);
        hexdump(payload, length);
        break;
    case sIOtype_BINARY_EVENT:
        USE_SERIAL.printf("[IOc] get binary: %u\n", length);
        hexdump(payload, length);
        break;
    case sIOtype_BINARY_ACK:
        USE_SERIAL.printf("[IOc] get binary ack: %u\n", length);
        hexdump(payload, length);
        break;
}

}

void setup() { USE_SERIAL.begin(115200);

//Serial.setDebugOutput(true);
USE_SERIAL.setDebugOutput(true);

USE_SERIAL.println();
USE_SERIAL.println();
USE_SERIAL.println();

  for(uint8_t t = 4; t > 0; t--) {
      USE_SERIAL.printf("[SETUP] BOOT WAIT %d...\n", t);
      USE_SERIAL.flush();
      delay(1000);
  }

// disable AP
if(WiFi.getMode() & WIFI_AP) {
    WiFi.softAPdisconnect(true);
}

WiFiMulti.addAP("TP-LINK_390", "25072015");

//WiFi.disconnect();
while(WiFiMulti.run() != WL_CONNECTED) {
    delay(100);
}

String ip = WiFi.localIP().toString();
USE_SERIAL.printf("[SETUP] WiFi Connected %s\n", ip.c_str());

// server address, port and URL
socketIO.begin("192.168.0.105", 8880);
// event handler
socketIO.onEvent(socketIOEvent);

}

unsigned long messageTimestamp = 0; void loop() { socketIO.loop();

uint64_t now = millis();

if(now - messageTimestamp > 2000) {
    messageTimestamp = now;

    // 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("join");

    // add payload (parameters) for the event
    JsonObject param1 = array.createNestedObject();
    param1["now"] = "esp is ready" ; //(uint32_t) now;

    // JSON to String (serializion)
    String output;
    serializeJson(doc, output);

    // Send event        
    socketIO.sendEVENT(output);

    // Print JSON for debugging
    USE_SERIAL.println(output);
}

}`

***************** And this is my code for nodejs server *********************************** `const http = require('http') const express = require('express') const socketio = require('socket.io')

const app = express() const server = http.createServer(app) const io = socketio(server) io.on('connection', (socket)=>{ console.log("New websocket connection") socket.on('join', (data)=>{ console.log(data) }) })`

Can anyone help me about this problem, please?

phungvanquy avatar Dec 11 '21 13:12 phungvanquy

You just need to change your server to

const http = require('http')
const express = require('express')
const socketio = require('socket.io')

const app = express()
const server = http.createServer(app)
const io = socketio(server)
io.on('connection', (socket)=>{
console.log("New websocket connection")
socket.on('join', (data)=>{
console.log(data)
})
})

server.listen(8880, () => {

  console.log("Server launched on port 8880");
})

or this better one

const app = require('express');
const http = require('http').createServer(app);
const io = require('socket.io')(http);

io.on('connection', (socket) => {

  console.log('Connected');
  console.log(socket.id);
  console.log("JWT token test: ",socket.handshake.headers)

  socket.on('join', (data) => {

    console.log("Message from Client : ", data);

    socket.broadcast.emit("Send Message socket.broadcast.emit : ", data);
    io.emit("Send Message io.emit Broadcasted : ", data);
    socket.emit("Send Message : ", data);

  })
  
  socket.on('disconnect', () => {

    console.log('Disconnected');

  })

})

http.listen(8880, () => {

  console.log("Server launched on port 8880");
})

khoih-prog avatar Dec 14 '21 02:12 khoih-prog