带有 EP32 客户端的 Nodejs Websocket 服务器

时间:2021-01-23 08:25:15

标签: node.js websocket esp32

我的 ESP32 客户端代码是,

#include <WiFi.h>
#include <WebSocketClient.h>
 
const char* ssid     = "###";
const char* password = "###";
 
char path[] = "/";
char host[] = "192.##.##.##";
 
WebSocketClient webSocketClient;
WiFiClient client;

void connnect(){
   if (client.connect(host, 5000)) {
    Serial.println("Connected");
  } else {
    Serial.println("Connection failed.");
  }
 
  webSocketClient.path = path;
  webSocketClient.host = host;
  if (webSocketClient.handshake(client)) {
    Serial.println("Handshake successful");
  } else {
    Serial.println("Handshake failed.");
  }
}
void setup() {
  Serial.begin(115200);
 
  WiFi.begin(ssid, password);
 
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
 
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
 
  delay(5000);
 
 connnect();
 
}
 
void loop() {
  String data;
 
  if (client.connected()) {
 
    webSocketClient.sendData("Info to be echoed back");
 
    webSocketClient.getData(data);
    if (data.length() > 0) {
      Serial.print("Received data: ");
      Serial.println(data);
    }
 
  } else {
    Serial.println("Client disconnected.");
    connnect();
  }
 
  delay(3000);
 
}

我在 Nodejs 中运行的 websocket 服务器是,

var WebSocketServer = require('websocket').server;
var http = require('http');

var server = http.createServer(function(request, response) {
    console.log((new Date()) + ' Received request for ' + request.url);
    response.writeHead(404);
    response.end();
});
server.listen(5000, function() {
    console.log((new Date()) + ' Server is listening on port 5000');
});

wsServer = new WebSocketServer({
    httpServer: server,
    // You should not use autoAcceptConnections for production
    // applications, as it defeats all standard cross-origin protection
    // facilities built into the protocol and the browser.  You should
    // *always* verify the connection's origin and decide whether or not
    // to accept it.
    autoAcceptConnections: false
});

function originIsAllowed(origin) {
  // put logic here to detect whether the specified origin is allowed.
  return true;
}

wsServer.on('request', function(request) {
    console.log(request)
    if (!originIsAllowed(request.origin)) {
      // Make sure we only accept requests from an allowed origin
      request.reject();
      console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
      return;
    }
    
    var connection = request.accept('echo-protocol', request.origin);
    console.log((new Date()) + ' Connection accepted.');
    connection.on('message', function(message) {
        if (message.type === 'utf8') {
            console.log('Received Message: ' + message.utf8Data);
            connection.sendUTF(message.utf8Data);
        }
        else if (message.type === 'binary') {
            console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
            connection.sendBytes(message.binaryData);
        }
    });
    connection.on('close', function(reasonCode, description) {
        console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
    });
});

当我运行这两个代码时,我收到的错误是,

错误:客户端未请求指定的协议。

我需要的是在 nodejs 上运行 websocket 服务器,ESP32 可以在其中作为客户端连接以发送和接收数据。请告诉我我做错了什么,因为上面代码中的错误不止一个。 如果有任何简单和更好的建议来编码 ESP32 和服务器,请建议我。提前致谢

1 个答案:

答案 0 :(得分:0)

我找到了问题的答案。 将 p + stat-ellipse() 替换为 request.accept('echo-protocol', request.origin)

相关问题