websocket._exceptions.WebSocketBadStatusException:握手状态 404 未找到

Posted

技术标签:

【中文标题】websocket._exceptions.WebSocketBadStatusException:握手状态 404 未找到【英文标题】:websocket._exceptions.WebSocketBadStatusException: Handshake status 404 NOT FOUND 【发布时间】:2019-05-02 14:30:26 【问题描述】:

我正在尝试通过 python 脚本与 Flask websocket 进行通信。但我收到以下异常。

Traceback (most recent call last):
  File "client.py", line 5, in <module>
    socket = create_connection("ws://127.0.0.1:5000")
  File "C:\Users\anyms\AppData\Local\Programs\Python\Python37-32\lib\site-packages\websocket\_core.py", line 514, in create_connection
    websock.connect(url, **options)
  File "C:\Users\anyms\AppData\Local\Programs\Python\Python37-32\lib\site-packages\websocket\_core.py", line 226, in connect
    self.handshake_response = handshake(self.sock, *addrs, **options)
  File "C:\Users\anyms\AppData\Local\Programs\Python\Python37-32\lib\site-packages\websocket\_handshake.py", line 79, in handshake
    status, resp = _get_resp_headers(sock)
  File "C:\Users\anyms\AppData\Local\Programs\Python\Python37-32\lib\site-packages\websocket\_handshake.py", line 160, in _get_resp_headers
    raise WebSocketBadStatusException("Handshake status %d %s", status, status_message, resp_headers)
websocket._exceptions.WebSocketBadStatusException: Handshake status 404 NOT FOUND

app.py

from flask import Flask
from flask_socketio import SocketIO, send


app = Flask(__name__)
app.config["SECRET_KEY"] = "uhjsbajksHGhksajjf^&*8*()"
socketio = SocketIO(app)


@socketio.on("message")
def message(msg):
    print("Message received: ".format(msg))
    send(msg, broadcast=True)


@socketio.on("connect")
def connect():
    print("Connected!")


if __name__ == "__main__":
    socketio.run(app)

client.py

#!/usr/bin/python

from websocket import create_connection

socket = create_connection("ws://127.0.0.1:5000")
socket.send("hello, world")

result = socket.recv()
print("Received: ".format(result))

socket.close()

如果我将 html 页面作为客户端编写,它可以正常工作,但我无法从我的 python 脚本连接。

当我使用ws://echo.websocket.org 时,它工作正常,我很困惑,我是 websocket 编程的新手。

【问题讨论】:

【参考方案1】:

现在一岁了,但基本上 websockets 和 socket.io 是创建套接字的两种不同方法。它们不兼容。您有一个 socket.io 服务器,但有一个 websocket 客户端。更改其中一个以匹配另一个,它应该可以工作。

【讨论】:

以上是关于websocket._exceptions.WebSocketBadStatusException:握手状态 404 未找到的主要内容,如果未能解决你的问题,请参考以下文章

Flask+gevent-websocket模块实现websocket

如何将 $_SESSION 变量传递给 websocket 服务器?

websocket._exceptions.WebSocketBadStatusException:握手状态 404 未找到

C#-WebSocket协议通讯_Net5

Unity+Firebase-Database [错误] WebSocket:ws_0 - 无法连接

php开启websocket服务,php实现简单的websocket服务