如何在线程中重用websocket通道?

2024-04-24 16:38:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在考虑在我的客户机(浏览器)-服务器(Python)应用程序中使用websockets,我很难理解如何跨线程重用websocket通道。你知道吗

我的应用程序将有几个线程,每个独立生成一些数据,我想推到浏览器。Getting Started examples清楚地表明,一旦浏览器连接到服务器,就会运行一个特定的函数(我从链接的文档复制了这个示例):

import asyncio
import datetime
import random
import websockets

async def time(websocket, path):
    while True:
        now = datetime.datetime.utcnow().isoformat() + 'Z'
        await websocket.send(now)
        await asyncio.sleep(random.random() * 3)

start_server = websockets.serve(time, '127.0.0.1', 5678)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

现在假设我有一个函数(worker)

def thread1(an_existing_webocket):
    while True:
        an_existing_webocket.send("1")
        print("1")
        time.sleep(1)

我想从threading.Thread(target=thread1, args=(an_initialized_websocket,)).start()开始。你知道吗

这两个世界(使用协程和threading的websockets)如何共存?更具体地说:我可以传递给工人什么样的websocket,以便他们可以使用它向上游发送消息?你知道吗

换句话说,我应该如何创建上面的an_initialized_websocket?你知道吗


Tags: 函数import服务器anasyncio应用程序datetimewebsockets