握手问题 Tornado 服务器和 ESP32 客户端
Posted
技术标签:
【中文标题】握手问题 Tornado 服务器和 ESP32 客户端【英文标题】:Handshake Issues Tornado Server and ESP32 Client 【发布时间】:2021-04-29 11:27:48 【问题描述】:我无法建立 websocket 连接。我使用 esp32 作为客户端,使用 Tornado Webserver 作为主机。 我可以使用 javascript 连接到主机,但我也可以将 esp32 连接到 websocket.org。 只有 esp32 和 Tornado Server 之间的连接不起作用。
ESP32 代码(Arduino IDE):
#include <WiFi.h>
#include <WebSocketClient.h> //By Markus Sattler
const char* ssid = "hadome";
const char* password = "12345678";
char path[] = "/ws";
char host[] = "192.168.178.29";
WebSocketClient webSocketClient;
WiFiClient client;
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);
if (client.connect(host, 3333))
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 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.");
delay(3000);
Python 代码摘录(龙卷风):
class WSHandler(tornado.websocket.WebSocketHandler):
def check_origin(self, origin):
return True
def open(self):
pass
def on_message(self, message):
self.write_message(message)
def on_close(self):
log('[WS] Connection was closed.')
application = tornado.web.Application([(r'/ws', WSHandler)])
# Main program logic follows:
if __name__ == '__main__':
# Tornado Server
try:
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(3333)
http_client = tornado.httpclient.AsyncHTTPClient()
http_client.initialize(1)
log("Tornado Server started")
tornado.ioloop.IOLoop.current().spawn_callback(loop)
tornado.ioloop.IOLoop.instance().start()
except:
log("Exception triggered - Tornado Server stopped.")
finally:
pass
ESP32 程序输出:
.......
WiFi connected
IP address:
192.168.2.8
Connected
Waiting...
Handshake failed.
我很困惑,因为这个 javascript 程序可以完美运行 (https://www.mischianti.org/2020/12/07/websocket-on-arduino-esp8266-and-esp32-client-1/):
var wsUri = "ws://192.168.178.29:3333/ws";
var output;
function init()
output = document.getElementById("output");
testWebSocket();
function testWebSocket()
websocket = new WebSocket(wsUri);
websocket.onopen = function (evt)
onOpen(evt)
;
websocket.onclose = function (evt)
onClose(evt)
;
websocket.onmessage = function (evt)
onMessage(evt)
;
websocket.onerror = function (evt)
onError(evt)
;
汉尼斯此致
PS:对不起我的英语不好
【问题讨论】:
【参考方案1】:我通过使用另一个库解决了这个问题。 (我使用 Markus Sattler 的图书馆)
【讨论】:
以上是关于握手问题 Tornado 服务器和 ESP32 客户端的主要内容,如果未能解决你的问题,请参考以下文章
Firebase - 切换到 WebSocket 协议 - 握手不起作用