1

I have a node server with express and socket io behind nginx reverse proxy at AWS. I am try to connect remotely from my NodeMCU esp8266 through websocket io client to my server using WebSocketClientSocketIO (unsuccessfully). I am new and don't know what I am doing wrong. Following are my debug messages. I keep on getting scandone.

SDK:2.2.1(cfd48f3)/Core:2.4.2/lwIP:2.0.3(STABLE-2_0_3_RELEASE/glue:arduino-2.4.1-13-g163bb82)/BearSSL:6d1cefc
del if0
usl
mode : null
mode : sta(84:f3:eb:b7:4e:8c)
add if0

Connecting.....scandone
state: 0 -> 2 (b0)
.state: 2 -> 3 (0)
state: 3 -> 5 (10)
add 0
aid 1
cnt

connected with Zlink, channel 13
dhcp client start...
....ip:192.168.10.8,mask:255.255.255.0,gw:192.168.10.1
.
Connected to Zlink
IP address: 192.168.10.8

[SETUP] BOOT WAIT 4...
[SETUP] BOOT WAIT 3...
[SETUP] BOOT WAIT 2...
[SETUP] BOOT WAIT 1...
state: 5 -> 0 (0)
rm 0
scandone
scandone
scandone
scandone
scandone
.
.
.
.

`

My sketch:

/*
 * WebSocketClientSocketIO.ino
 *
 *  Created on: 06.06.2016
 *
 */
#include <Arduino.h>

#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <WiFiClient.h> 
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>
#include <WebSocketsClient.h>
#include <Hash.h>
ESP8266WiFiMulti WiFiMulti;
WebSocketsClient webSocket;
const char *ssid = "MyWiFiName";  
const char *password = "mypassword";
#define USE_SERIAL Serial
#define MESSAGE_INTERVAL 30000
#define HEARTBEAT_INTERVAL 25000
uint64_t messageTimestamp = 0;
uint64_t heartbeatTimestamp = 0;
bool isConnected = false;
void webSocketEvent(WStype_t type, uint8_t * payload, size_t length) {
    switch(type) {
        case WStype_DISCONNECTED:
            USE_SERIAL.printf("[WSc] Disconnected!\n");
            isConnected = false;
            break;
        case WStype_CONNECTED:
            {
                USE_SERIAL.printf("[WSc] Connected to url: %s\n",  payload);
                isConnected = true;
        // send message to server when Connected
                // socket.io upgrade confirmation message (required)
                webSocket.sendTXT("5");
            }
            break;
        case WStype_TEXT:
           USE_SERIAL.printf("[WSc] get text: %s\n", payload);
                        // send message to server
            // webSocket.sendTXT("message here");
            break;
        case WStype_BIN:
            USE_SERIAL.printf("[WSc] get binary length: %u\n", length);
                        hexdump(payload, length);
            // send data to server
            // webSocket.sendBIN(payload, length);
            break;
    }
};
void setup() {
  delay(1000); 
    // USE_SERIAL.begin(921600);
    USE_SERIAL.begin(115200);
  WiFi.mode(WIFI_OFF);        //Prevents reconnection issue (taking too long to connect)
  delay(1000);
  WiFi.mode(WIFI_STA);        //This line hides the viewing of ESP as wifi hotspot
 startWiFi();
    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);
      }

   // WiFiMulti.addAP("SSID", "passpasspass");

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


```   // webSocket.beginSocketIO("192.168.0.123", 81);
      webSocket.beginSocketIO("http://www.myDomainName.com", 80, "/addr");
 //addr is address where I want to send messages
    //webSocket.setAuthorization("user", "Password"); // HTTP Basic Authorization
    webSocket.onEvent(webSocketEvent);
}
void loop() {
webSocket.loop();
testSend();
    if(isConnected) {
        uint64_t now = millis();
        if(now - messageTimestamp > MESSAGE_INTERVAL) {
            messageTimestamp = now;
            // example socket.io message with type "messageType" and JSON payload
            webSocket.sendTXT("42[\"messageType\",{\"greeting\":\"hello\"}]");
        }
        if((now - heartbeatTimestamp) > HEARTBEAT_INTERVAL) {
            heartbeatTimestamp = now;
            // socket.io heartbeat message
            webSocket.sendTXT("2");
        }
    };
};
void startWiFi() {
   WiFi.begin(ssid, password);     
  USE_SERIAL.println("");
  USE_SERIAL.print("Connecting");
  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    USE_SERIAL.print(".");
  };
  //If connection successful show IP address in serial monitor
  USE_SERIAL.println("");
  USE_SERIAL.print("Connected to ");
  USE_SERIAL.println(ssid);
  USE_SERIAL.print("IP address: ");
  USE_SERIAL.println(WiFi.localIP());  //IP address assigned to your ESP
  };
void testSend(){
   webSocket.sendTXT("Hello from esp");
   delay(1000);
  };
`
My code on node server where I am trying to collect messages from esp8266 is very simple as bellow:

socket.on('addr1', function (req,res) {
   console.log(req);
   });
Zeni
  • 111
  • 4
  • 1
    why call `WiFi.disconnect()` towards the end of setup , after you waited to connect? – dandavis Aug 29 '18 at 15:49
  • Thanks fellows. I will consider both points and post results. I will remove wifi Multi cause I don't understand why we need to use access point while all I need is to use socket io CLIENT in my code? – Zeni Aug 31 '18 at 11:24
  • it is not use of AP. you connect to an AP to join the WiFi network. with WiFiMulti more APs can be set to connect to. it is good if the esp8266 changes location (home, work, mobile hotspot, ... ) – Juraj Sep 04 '18 at 16:49

2 Answers2

1

Try to use your Local IP as your client WebSocket.

...
...
const char* host = "192.168.x.x";
WifiClient wificlient;
...
...

void setup(){
  ...
  ...
  startWiFi();
  //WiFi.mode(WIFI_OFF);
  //WiFi.disconnect();
  if(!wificlient.connect(host, 80)){
    Serial.println(F("connection failed! "));
    return;
  }
  client.setClient(wificlient);
  ...
  ...
}

also add your host on the express NodeJS. I found a issue like your this

...
...
var http = require('http').Server(app);
var io = require('socket.io')(http);
var host = "192.168.x.x";
var port = "80";
...
...
socket.emit("<your-text>");
server.listen(host, port, function(){
  console.log("listening on http://"+host+":"+host+" ");
});
...
...  

Hope this helps.

0

in the sketch 'simple WiFi begin() is mixed with WiFiMulti system. first the sketch connects to AP and then disconnects and starts WiFiMulti. but:

no AP is configured for WiFiMulti to connect

Juraj
  • 17,050
  • 4
  • 27
  • 43
  • I removed following lines from my code above: WiFi.disconnect(), and WiFiMulti – Zeni Sep 04 '18 at 14:23
  • and? is it better? – Juraj Sep 04 '18 at 14:26
  • Now to connect to socket io server I have this line '' ' webSocket.beginSocketIO("http://localhost", 8080 , "/espSocketSrvr2" ); ' But I am getting error //[WS-Client] connect ws... [WS-Client] connection to http://myserver.com:80 Faild [WS-Client] client disconnected. [WSc] Disconnected! ' – Zeni Sep 04 '18 at 14:35
  • I also tried running simple socket server using ws library. I changed connection line to `webSocket.begin("127.0.0.1", 8080 , "/" );` . Still I get error ` [WS-Client] connect ws... [WS-Client] connection to 127.0.0.1:8080 Faild [WS-Client] client disconnected. [WSc] Disconnected! ` . Though I can connect to server through socket from browser in both cases. I guess I am missing some small thing, but what is that ...............,.. – Zeni Sep 04 '18 at 14:40
  • I am running node js server on local computer. I also tried ` webSocket.begin("http://localhost", 8080 , "/" );` without success. – Zeni Sep 04 '18 at 14:57
  • localhost of your esp8266 is your esp8266 – Juraj Sep 04 '18 at 14:59
  • Great point!!!! Let me try using my IP. – Zeni Sep 04 '18 at 15:07
  • Still same problem. [WS-Client] connect ws... [WS-Client] connection to myip:8080 Faild [WS-Client] client disconnected. [WSc] Disconnected! – Zeni Sep 04 '18 at 15:09
  • but the original question is solved or not? – Juraj Sep 04 '18 at 15:10
  • Unfortunately not. Any way it is late night here. Will try again tomorrow. Lot of thanks dear Juraj. – Zeni Sep 04 '18 at 15:12
  • but the esp8266 is connected to WiFi network or it is still "scandone"? – Juraj Sep 04 '18 at 16:45