Unable to get ESP8266 to connect to a websocket server on heroku

610 views Asked by At

I have a working websocket server running on heroku with a basic code.

var WebSocketServer = require("ws").Server
var http = require("http")
var express = require("express")
var app = express()
var port = process.env.PORT || 5000

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

var server = http.createServer(app)
server.listen(port)

console.log("http server listening on %d", port)

var wss = new WebSocketServer({server: server})
console.log("websocket server created")

wss.on("connection", function(ws) {
  var id = setInterval(function() {
    ws.send(JSON.stringify(new Date()), function() {  })
  }, 1000)

  console.log("websocket connection open")

  ws.on("close", function() {
    console.log("websocket connection close")
    clearInterval(id)
  })
})

And have this code on ESP8266:

#include <Arduino.h>
#include "WebSocketClient.h"
#include "ESP8266WiFi.h"

WebSocketClient ws(true);

void setup() {
  Serial.begin(115200);
  WiFi.begin("SSID", "PASSWORD");

  Serial.print("Connecting");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
}

void loop() {
  if (!ws.isConnected()) {
    ws.connect("iot-home-project.herokuapp.com", "/",80);
    Serial.println("Not connected!");
  } else {
    ws.send("hello");

    String msg;
    if (ws.getMessage(msg)) {
      Serial.println(msg);
    }
  }
  delay(500);
}

The websocket server is fine based on the test I did using https://www.websocket.org/echo.html But the ESP8266 just prints Not Connected on the Serial Monitor. Things that I have noticed:

  • Each time ESP8266 tries to connect, the webserver prints socket open and then immediately socket close
0

There are 0 answers