【问题标题】:reading data from websocket without blocking the code从 websocket 读取数据而不阻塞代码
【发布时间】:2019-06-04 06:17:31
【问题描述】:

我正在尝试使用 python 的 asyncio 编写非阻塞代码。关于这个主题有几个线程,但我仍然没有设法使它们适应代码。这将是一个基于this 的最小示例:

import asyncio
import websockets

async def ws_rec(websocket, path):
    while True:
        data = await websocket.recv()       
        print(data)

start_server = websockets.serve(ws_rec, 'localhost', 8765)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
print("ok")

如何调整代码以打印“ok”?为什么我什至需要 asyncio?

【问题讨论】:

  • 运行事件循环接管调用线程,但 asyncio 允许您轻松安排其他非阻塞代码运行(事实上,这就是它的用途)。例如,您可以使用asyncio.create_task(your_coroutine()) 并定义async def your_coroutine(): print("ok")。
  • 感谢您的快速回复。不幸的是,我的代码是基于线程的。我是否必须将所有内容都重写为 asyncio 或者是否有其他选择?
  • 理想情况下,您应该全面使用 asyncio。但如果这不可行,您也可以在专用线程中运行 asyncio 事件循环,如 this answer 中所述(在选项 #3 下)。

标签: python websocket python-asyncio nonblocking


【解决方案1】:

非常感谢您的回答。 我找到了一种使用 simple-websocket 的解决方法

from simple_websocket_server import WebSocketServer, WebSocket

class SimpleEcho(WebSocket):
    def handle(self):
    # echo message back to client
        print(self.data)
        self.send_message(self.data)

    def connected(self):
        print(self.address, 'connected')

    def handle_close(self):
        print(self.address, 'closed')


def run():
    server = WebSocketServer('localhost', 8765, SimpleEcho)
    server.serve_forever()

from threading import Thread

ws_run = Thread(target=run)
ws_run.start()

print("ok")

现在,这对我来说似乎是一个可行的解决方案。

【讨论】:

    猜你喜欢
    • 2022-01-02
    • 2011-06-25
    • 1970-01-01
    • 2018-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多