【问题标题】:Python to Python WebSockets with websockets and flask-socketio带有 websockets 和 flask-socketio 的 Python 到 Python WebSockets
【发布时间】:2019-04-05 13:15:40
【问题描述】:

问题

所以我需要制作一个可以放在机器上的 python 应用程序,打开一个 websocket 管道到运行 flask-socketio 的服务器,然后将数据通过管道传输到服务器。数据将是 json 数据,现在我正在使用字符串进行测试。

我在使用 python 中的“websockets”库连接到我正在制作的“flask-socketio”后端时遇到问题。

代码

服务器

from flask import Flask, render_template, request, url_for, 

copy_current_request_context
from flask_socketio import SocketIO, emit
import logging

logging.basicConfig()

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True
socketio = SocketIO(app)


@socketio.on('connect', namespace='/')
def connect():
    print('Client connected')


@socketio.on('disconnect', namespace='/')
def disconnect():
    print('Client disconnected')


if __name__ == '__main__':
    socketio.run(app, debug=True)

客户端 1 - websockets 库

import asyncio
import websockets

async def hello():
    async with websockets.connect(
            'ws://127.0.0.1:5000') as websocket:
        name = 'joe'  # input("What's your name? ")

        await websocket.send('message', name)
        print(f"> {name}")

        greeting = await websocket.recv()
        print(f"< {greeting}")

asyncio.get_event_loop().run_until_complete(hello())

print("end")

使用输出

当我使用客户端 1 时,我将其作为客户端进程的输出: Traceback (most recent call last): File "C:/project_files/aWebUAS/micro-services/New-Capabilities-Investigation/web_socket_client.py", line 15, in <module> asyncio.get_event_loop().run_until_complete(hello()) File "C:\Program Files\Anaconda3\lib\asyncio\base_events.py", line 466, in run_until_complete return future.result() File "C:/project_files/aWebUAS/micro-services/New-Capabilities-Investigation/web_socket_client.py", line 6, in hello 'ws://127.0.0.1:5000') as websocket: File "C:\Program Files\Anaconda3\lib\site-packages\websockets\py35\client.py", line 2, in __aenter__ return await self File "C:\Program Files\Anaconda3\lib\site-packages\websockets\py35\client.py", line 20, in __await_impl__ extra_headers=protocol.extra_headers, File "C:\Program Files\Anaconda3\lib\site-packages\websockets\client.py", line 286, in handshake raise InvalidStatusCode(status_code) websockets.exceptions.InvalidStatusCode: Status code not 101: 404

在烧瓶过程中我看到了:
127.0.0.1 - - [2019-04-05 09:17:13] "GET / HTTP/1.1" 404 342 0.000999

客户端 2 - websocket 客户端库

import websocket
ws = websocket.WebSocket()
ws.connect("ws://127.0.0.1:5000")
ws.send("Hello, World")

使用输出

在客户端 2 进程中,我将其作为输出: Traceback (most recent call last): File "C:/project_files/aWebUAS/micro-services/New-Capabilities-Investigation/web_socket_client_2.py", line 3, in <module> ws.connect("ws://127.0.0.1:5000") File "C:\Program Files\Anaconda3\lib\site-packages\websocket\_core.py", line 226, in connect self.handshake_response = handshake(self.sock, *addrs, **options) File "C:\Program Files\Anaconda3\lib\site-packages\websocket\_handshake.py", line 79, in handshake status, resp = _get_resp_headers(sock) File "C:\Program Files\Anaconda3\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

烧瓶过程显示如下:
127.0.0.1 - - [2019-04-05 09:11:57] "GET / HTTP/1.1" 404 342 0.001000

结论

一些阅读告诉我,我没有正确地在烧瓶中使用我的 socketio 处理程序,但我不确定如何定位它。

非常感谢任何帮助。我的目标是让 python 脚本与烧瓶 socketio 服务器对话。我没有与任何部分结婚,但更愿意坚持使用烧瓶作为服务器。

TIA - 伊恩

【问题讨论】:

    标签: flask websocket socket.io python-3.6


    【解决方案1】:

    您现在可能已经想通了,但问题可能在于 flask-socketio 是一个 Socket.IO 实现,而不是一个 websocket 实现。 Socket.IO 使用 websockets 作为其通信协议之一,但您需要一个 Socket.IO 客户端来连接到 flask-socketio 服务器。

    socketio's docs,具体来说:

    Socket.IO 不是 WebSocket 实现。虽然 Socket.IO 确实 尽可能使用 WebSocket 作为传输,它会添加一些元数据到 每个数据包:数据包类型、命名空间和确认 ID 需要消息确认。这就是为什么 WebSocket 客户端会 无法成功连接到 Socket.IO 服务器,并且 Socket.IO 客户端将无法连接到 WebSocket 服务器 要么。

    看看这个 python Socket.IO 客户端。 https://github.com/miguelgrinberg/python-socketio

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-05
      • 1970-01-01
      • 2014-05-20
      • 1970-01-01
      • 1970-01-01
      • 2013-03-27
      相关资源
      最近更新 更多