You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ESP-01S(ESP8266)与Arduino的WebSocket连接失败求助

问题

我是WebSocket与Arduino开发新手,正在尝试用ESP-01S连接另一台电脑上的WebSocket服务器。目前已成功连接WiFi并获取本地IP,也能通过GET请求与服务器通信,但WebSocketClient连接始终无法建立。我使用的是Arduino UNO和ESP-01S模块,尝试过连接自建服务器(已验证其他PC可正常连接)和公共服务器如echo.websocket.org,均仅收到“Disconnected from WebSocket”消息,预期应显示“Connected to WebSocket”。

代码如下:

#include <ESP8266WiFi.h>
#include <WebSocketsClient.h>
#include <ESP8266HTTPClient.h>

const char* ssid = "my ssid";
const char* password = "my pass";
const char* webSocketServer = "my ws ip";
const int webSocketPort = 3000;
const char* targetIP = "my ws ip";  
const int targetPort = 3000;
 
WiFiClient client;
WebSocketsClient webSocket = WebSocketsClient();

void setup() {
  Serial.begin(57600);
  Serial.println("Initializing...");

  // Connect to WiFi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  Serial.println("Connected to WiFi");

  // Connect to WebSocket server
  Serial.println("Attempting to connect to WebSocket server...");
  webSocket.begin("echo.websocket.org", 80, "/");

  webSocket.onEvent(webSocketEvent);
 
  makeGETRequest();
  Serial.println("Setup complete");
}

void loop() {

  webSocket.loop();
}

void webSocketEvent(WStype_t type, uint8_t * payload, size_t length) {
  switch(type) {
    case WStype_DISCONNECTED:
      Serial.println("Disconnected from WebSocket");
      break;
    case WStype_CONNECTED:
      Serial.println("Connected to WebSocket");
      break;
    case WStype_TEXT:
      Serial.printf("Received payload: %s\n", payload);
      break;
  }
}

void printIPAddress() {
  // Get and print the local IP address
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);
}

void makeGETRequest() {
  // Create a WiFiClient object to establish a connection
  WiFiClient client;

  // Create an HTTPClient object
  HTTPClient http;

  // Construct the complete URL with the target IP and port
  String url = "http://" + String(targetIP) + ":" + String(targetPort);

  Serial.print("Making GET request to: ");
  Serial.println(url);

  // Begin the HTTP request
  if (http.begin(client, url)) {
    // Send the GET request
    int httpCode = http.GET();

    // Check the HTTP response code
    if (httpCode > 0) {
      Serial.print("HTTP response code: ");
      Serial.println(httpCode);

      // Print the response payload
      String payload = http.getString();
      Serial.println("Response payload:");
      Serial.println(payload);
    } else {
      Serial.println("Failed to get HTTP response");
    }

    // Close the connection
    http.end();
  } else {
    Serial.println("Failed to begin HTTP connection");
  }
}

请问我哪里操作出错了?希望得到帮助。


排查与解决建议

1. 修复WebSocket事件回调的设置顺序

你的代码里先调用webSocket.begin(),再设置webSocket.onEvent(webSocketEvent),这会导致事件回调无法被正确注册,连成功的消息也无法触发。正确顺序应该是先绑定事件,再发起连接:

// 先设置事件回调
webSocket.onEvent(webSocketEvent);
// 再初始化WebSocket连接
webSocket.begin("echo.websocket.org", 80, "/");

2. 测试自建服务器时需替换正确的服务器地址

当前代码里硬编码了echo.websocket.org,如果你要测试自己的服务器,需要把这里换成你的服务器IP和端口:

webSocket.begin(webSocketServer, webSocketPort, "/");
// 注意替换成你实际的WebSocket端点路径,比如服务器是/ws的话就写"/ws"

3. 检查网络与服务器配置

  • 确认ESP-01S和你的服务器处于同一局域网,或者服务器有公网IP且端口(3000)已开放防火墙/端口映射
  • 验证服务器的WebSocket端点是否正确:比如有些服务器需要指定特定路径(如/ws),而不是根路径/
  • 尝试调整串口波特率(比如改为115200),确认与ESP-01S的默认波特率一致

4. 添加重连逻辑(可选)

如果连接不稳定,可以在WStype_DISCONNECTED事件里添加重连代码,避免单次失败后无法恢复:

case WStype_DISCONNECTED:
  Serial.println("Disconnected from WebSocket, retrying...");
  delay(3000);
  webSocket.begin(webSocketServer, webSocketPort, "/"); // 替换成你的服务器信息
  break;

内容的提问来源于stack exchange,提问作者Alejandro Angel Rivera

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 21:04:58