Bootstrap

8266使用websocket库

安装 WebSocket 库

  1. 使用 Arduino IDE 安装

    • 打开 Arduino IDE。
    • 转到 Sketch > Include Library > Manage Libraries...
    • 在搜索框中输入“WebSockets”并查找 WebSockets by Markus Sattler 的库。
    • 点击安装。

  2. 最下面那个,安装
  3. 编译运行测试,通过,没问题

下来我贴一些测试代码

#include <WebSocketsServer.h>
#include <ESP8266WiFi.h>

// 替换为你的WiFi网络凭据
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";

// WebSocket服务器端口
WebSocketsServer webSocket = WebSocketsServer(81);

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  // 启动WebSocket服务器
  webSocket.begin();
  webSocket.on("message", handleWebSocketMessage);
  Serial.println("WebSockets started");
}

void loop() {
  webSocket.loop();
}

void handleWebSocketMessage(uint8_t num, WStype_t type, uint8_t *payload, size_t length) {
  if (type == WStype_TEXT) {
    Serial.printf("Received message: %s\n", payload);
    webSocket.sendTXT(num, "Message received");
  }
}

;