Arduino Client 通过 websocketsocket 连接到服务器但无法与之通信

Arduino Client connects to server through websocketsocket but can't communicate with it

我在 esp8266 wifi 板上有这个客户端 运行,代码如下:

#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>

ESP8266WiFiMulti WiFiMulti;
String line="";

void setup() {
    Serial.begin(115200);
    delay(10);

    // We start by connecting to a WiFi network
    WiFiMulti.addAP("MYSSID", "MYPASSWORD");

    Serial.println();
    Serial.println();
    Serial.print("Wait for WiFi... ");

    while(WiFiMulti.run() != WL_CONNECTED) {
        Serial.print(".");
        delay(500);
    }

    Serial.println("");
    Serial.println("WiFi connected");
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());

    delay(500);
}

void loop() {
    const uint16_t port = 5021;
    const char * host = "192.168.x.yyy";
    
    Serial.print("connecting to ");
    Serial.println(host);

    // Use WiFiClient class to create TCP connections
    WiFiClient client;

    if (!client.connect(host, port)) {
        Serial.println("connection failed");
        delay(1000);
        return;
    }

  // This will send the request to the server
  Serial.println("Connected!!!!!");
  const char * frame = "009TEMSDS&000001001023";
  client.print(frame);
               
  delay(1000);

   while(client.available()){
    String line = client.readStringUntil('\r');
    Serial.print(line);
  }

  //Serial.println(line);
    Serial.println("closing connection");
    client.stop();
    
    delay(1000);
}

我希望它连接到我计算机上的 python websocket 服务器:

#!/usr/bin/env python

import asyncio
import websockets
import threading

framesReceive = []

async def receiver(websocket, path):
    framesReceive = (await websocket.recv())
    print(framesReceive)
    # dictFrame = frameBreakdown(framesReceive)

    await websocket.send("pong")

# Socket Server thread
def ThreadServer():
    asyncio.set_event_loop(asyncio.new_event_loop())
    start_server = websockets.serve(receiver, "192.168.x.yyy", 5021)
    asyncio.get_event_loop().run_until_complete(start_server)
    asyncio.get_event_loop().run_forever()

threadServer = threading.Thread(target=ThreadServer, args=())
threadServer.start()

简而言之,没有发送消息“009TEMSDS&000001001023”,也没有收到响应“pong”。

Even if a connection is in fact being established(image)

and when i try to send the same message from a client within my computer it works as expected(image)

我错过了什么吗? 为什么收不到客户的消息?

您分享的 ESP8266 代码没有使用 websockets 客户端。它使用原始 TCP 连接。 WiFiClient 只是打开一个到服务器的 TCP 连接;它在该连接上既不提供 HTTP 也不提供 websockets。您将需要另一个使用 WiFiClient 的库来执行此操作。

如果您想使用 websockets 与您的 Python 代码通信,您需要在 ESP8266 上使用 websocket 客户端。我想知道,为什么? Websockets 主要用于绕过网络浏览器的限制——您不需要为 ESP8266 使用 websockets 来与同一网络上的 Python 脚本通信。 websockets 更常见的用例是 Javascript 运行 在浏览器中与 websocket 服务器通信。

有一些不同的 ESP8266 websocket 客户端库;使用 Google 查找仍然受支持且适合您需要的版本。 this library 可能对您有用。

我建议您只需重写 Python 服务器以使用接受原始 TCP 连接,而不必担心在这种情况下使用 websockets。