我正在尝试通过 Web 套接字将 ESP32 与本地 Nodejs 服务器连接。 我在 CLion 上使用 PlatformIO Arduino 环境(我不知道知道是否有用)。
ESP32成功连接了WiFi,也可以读取服务器页面的内容(我是测试的),但是似乎无法连接SocketIO websocket,我到处找了也没找到,我希望你能帮助我。
ESP32代码:
#include <Arduino.h>
#include <WebSocketsClient.h>
#include <HTTPClient.h>
WebSocketsClient websocket;
boolean connected = false
void webSocketEvent(WStype_t type, uint8_t * payload, size_t length) {
switch(type) {
case WStype_DISCONNECTED:
Serial.printf("[WSc] Disconnected!\n");
connected = false;
break;
case WStype_CONNECTED:
digitalWrite(MESSAGE_LED_PIN, HIGH);
Serial.printf("[WSc] Connected to url: %s\n", payload);
connected = true;
}
void setup() {
Serial.begin(115200);
WiFi.begin("SSID", "PASSW");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("Connesso al WiFi");
Serial.println(WiFi.localIP());
inviaRichiestaHTTP(); // I don't enter the code of this function
websocket.begin("192.168.1.16",3000,"/socket.io/?EIO=4");
websocket.onEvent(webSocketEvent);
}
void loop() {
websocket.loop();
}
系列:
....
Connesso al WiFi
192.168.1.170
[HTTP] Codice di stato: 200
<h1>Hello world</h1>
[WSc] Disconnected!
[WSc] Disconnected!
[WSc] Disconnected!
Nodejs 服务器:
const ip = require("ip");
var app = require('express')();
var server = require('http').createServer(app);
var io = require('socket.io')(server); //pass a http.Server instance
var port = process.env.PORT 80;
app.get('/', function (req, res) {
//check sender ip
var senderip = req.headers['x-forwarded-for'] req.connection.remoteAddress;
console.log('sender ip: '+senderip);
res.send('<h1>Hello world</h1>');
});
io.on('connection', function (socket) {
console.log('Client connected');
socket.on('message', function (data) {
console.log('Message received: ', data);
});
socket.on('disconnect', function () {
console.log('Client disconnected');
});
});
server.listen(port);
如果我没记错的话,应该使用完整的 URL(包括协议)调用 websocket.begin() 方法。另外,您需要确保 WebSocket 连接使用 Socket.IO 服务器的正确路径。试试这个,看看是否有效,
// before update
websocket.begin("192.168.1.16", 3000, "/socket.io/?EIO=4");
// after update
websocket.begin("ws://192.168.1.16:3000/socket.io/?EIO=4"); // if you find that it doesn't work, you may want to try http:// for the WebSocket URL.