无法使ESP8266连接到heroku上的websocket服务器

无法使ESP8266连接到heroku上的websocket服务器,websocket,arduino,esp8266,ws,Websocket,Arduino,Esp8266,Ws,我有一个运行在heroku上的websocket服务器,带有基本代码 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(__

我有一个运行在heroku上的websocket服务器,带有基本代码

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)
  })
})
在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);
}
#包括
但ESP8266仅在串行监视器上打印未连接的
。 我注意到的事情:

  • 每次ESP8266尝试连接时,Web服务器都会打印
    套接字打开
    ,然后立即
    套接字关闭

您的回音测试表明它正在使用wss(SSL上的ws),但您的客户端代码不是。我在使用ESP8266上的wss时遇到问题,因此改用不安全的ws。如何使ESP8266和服务器使用ws进行通信?如果您使用的是面向公众的Heroko,您可能必须使用wss,为了做到这一点,您需要建立一个安全的WiFiClient,请查看示例的示例。您的回显测试表明它使用的是wss(ws over SSL),但您的客户端代码不是。我在使用ESP8266的wss时遇到问题,因此转而使用不安全的ws。如何使ESP8266和服务器使用ws进行通信?如果您使用的是面向公众的Heroko,您可能必须使用wss,为了做到这一点,您需要建立一个安全的WiFiClient,请查看示例的。