Links2004 / arduinoWebSockets

arduinoWebSockets
GNU Lesser General Public License v2.1
1.87k stars 553 forks source link

I can't connect SocketIOclient with SocketIO server in nodejs with express #579

Closed bkdrp closed 3 years ago

bkdrp commented 3 years ago

good night, I'm trying to connect a SocketIO server made in nodejs with express and socket.io and communicate events to my esp8266 F12, but I can't connect correctly, since it always appears to me that it could not connect, but in the debug mode of the serial It shows me that http has code 200, which from what I understand it was possible to connect to the web.

this is what the serial throws me:

05:38:47.945 -> [WS-Client] connect ws...
05:38:47.945 -> [hostByName] Host: 192.168.0.49 is a IP!
05:38:47.945 -> :ref 1
05:38:47.945 -> [WS-Client] connected to 192.168.0.49:3000.
05:38:47.945 -> [WS-Client][sendHeader] sending header...
05:38:47.945 -> [WS-Client][sendHeader] handshake GET /socket.io/?EIO=3&transport=polling HTTP/1.1
05:38:47.945 -> Host: 192.168.0.49:3000
05:38:47.945 -> Connection: keep-alive
05:38:47.945 -> Origin: file://
05:38:47.945 -> User-Agent: arduino-WebSocket-Client
05:38:47.945 -> 
05:38:47.945 -> [write] n: 156 t: 2139412
05:38:47.979 -> :wr 156 0
05:38:47.979 -> :wrc 156 156 0
05:38:47.979 -> [WS-Client][sendHeader] sending header... Done (28965us).
05:38:47.979 -> [wsIOc] send ping
05:38:47.979 -> [WS][0][sendFrame] not in WSC_CONNECTED state!?
05:38:47.979 -> :ack 156
05:38:47.979 -> :rn 260
05:38:47.979 -> [WS-Client][handleHeader] RX: HTTP/1.1 200 OK
05:38:47.979 -> [WS-Client][handleHeader] RX: Content-Type: text/plain; charset=UTF-8
05:38:47.979 -> [WS-Client][handleHeader] RX: Content-Length: 96
05:38:47.979 -> [WS-Client][handleHeader] RX: Date: Wed, 18 Nov 2020 10:38:47 GMT
05:38:48.014 -> [WS-Client][handleHeader] RX: Connection: keep-alive
05:38:48.014 -> [WS-Client][handleHeader] RX: Keep-Alive: timeout=5
05:38:48.014 -> [WS-Client][handleHeader] Header read fin.
05:38:48.014 -> [WS-Client][handleHeader] Client settings:
05:38:48.014 -> [WS-Client][handleHeader]  - cURL: /socket.io/?EIO=3
05:38:48.014 -> [WS-Client][handleHeader]  - cKey: 6YPY24hco/LCNbaGqx6X5Q==
05:38:48.014 -> [WS-Client][handleHeader] Server header:
05:38:48.014 -> [WS-Client][handleHeader]  - cCode: 200
05:38:48.048 -> [WS-Client][handleHeader]  - cIsUpgrade: 0
05:38:48.048 -> [WS-Client][handleHeader]  - cIsWebsocket: 0
05:38:48.048 -> [WS-Client][handleHeader]  - cAccept: 
05:38:48.048 -> [WS-Client][handleHeader]  - cProtocol: arduino
05:38:48.048 -> [WS-Client][handleHeader]  - cExtensions: 
05:38:48.048 -> [WS-Client][handleHeader]  - cVersion: 0
05:38:48.048 -> [WS-Client][handleHeader]  - cSessionId: 
05:38:48.048 -> [WS-Client][handleHeader] no Websocket connection close.
05:38:48.048 -> [write] n: 27 t: 2139516
05:38:48.082 -> :wr 27 0
05:38:48.082 -> :wrc 27 27 0
05:38:48.082 -> :ack 27
05:38:48.082 -> :rcl pb=0x3fff15cc sz=260
05:38:48.082 -> :close
05:38:48.082 -> :ur 1
05:38:48.082 -> :dsrcv 260
05:38:48.082 -> :del
05:38:48.082 -> [WS-Client] client disconnected.
05:38:48.082 -> [IOc] Disconnected!
05:38:48.082 -> [wsIOc] Disconnected!
05:38:48.082 -> ["event_name",{"now":2139545}]

this is my code in nodejs:

I have tried this code

var PORT = process.env.PORT || 3000;
var express = require('express');
var app = express();
var http = require('http');
var server = http.Server(app); 

var io = require('socket.io')(server);

    var PORT = process.env.PORT || 3000;
    const app = require('express')();
    const server = require('http').createServer(app);
   //   const options = {            };
    const io = require('socket.io')(server, options);

    //console.log(io);
    //io.on('WSC_CONNECTED', socket => {console.log('a user connection'); });

io.on('connection', function (socket) 
{
    console.log('a user connection');
});

io.on('connect', function (socket) 
{
    console.log('a user connectado');
});

io.on('request', function (socket) 
{
    console.log('a user request');
});

server.listen(PORT, function () 
{
    console.log('web iniciada en *:' + PORT);
}
); 

and also this

const io = require('socket.io')(3000);
//console.log('socket id: en puerto 3000');
console.log(io);

    io.on('connection', (socket) => {
        console.info('[' + socket.id + '] new connection', socket.request.connection.remoteAddress);

        var cb_test = 0;
        socket.on('event_name', function(data) {
            console.log('[' + socket.id + '] IN:', data);
            socket.emit('no-cb-test');
            socket.emit('cb-test', cb_test++,  function(id) {
                console.log('cb-test OK', id);
            });
        });

        socket.on('reconnect', function() {
            console.warn('[' + socket.id + '] reconnect.');
        });

        socket.on('disconnect', () => {
            console.error('[' + socket.id + '] disconnect.');
        });
    });

But neither of the 2 reads me socketid connections.

This is my test code for the ESP 8266

/*
 * WebSocketClientSocketIO.ino
 *
 *  Created on: 06.06.2016
 *
 */

  #define WBSSID "MYRED"
  #define PASSWORD "MYPASS"
  #define URL "192.168.0.49" // "my.socket-io.server"
  #define PUERTO 3000 // "my.socket-io.server"

#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);
            break;
        case sIOtype_EVENT:
            USE_SERIAL.printf("[IOc] get event: %s\n", payload);
            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(921600);
    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(WBSSID, PASSWORD);

    //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 (Inicia la secuencia de conexión al host websocket.)
    socketIO.begin(URL , PUERTO ); // parametros (ip servidor io , puerto, url en la ip, protocolo)

    // event handler
    socketIO.onEvent(socketIOEvent);//Devolución de llamada para manejar eventos websocket
}

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

        // add payload (parameters) for the event
        JsonObject param1 = array.createNestedObject();
        param1["now"] = (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);
    }
}

This is the web socket IO version that I use for arduino.

Please help me to be able to correctly make the code to be able to make the connection and transmit data between the server and the esp8266. Thank you and excuse my English :).

Links2004 commented 3 years ago

which version of socket.io do you use for your server? in version 3 of the socket.io protocol there where some changes, the lib is currently not adapted to this.

tracked in: https://github.com/Links2004/arduinoWebSockets/issues/576

bkdrp commented 3 years ago

You were right, I changed to version 2.3.0 and I walked, thanks I had not noticed that detail.

skakwy commented 3 years ago

You were right, I changed to version 2.3.0 and I walked, thanks I had not noticed that detail.

can you send the arduino code and the nodejs script please

Links2004 commented 3 years ago

Support for Socket.IO 3 has been Implemented Released with version 2.3.1 of this lib