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

时间:2017-11-02 14:27:55

标签: python multithreading websocket coroutine

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

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

<input type='checkbox' name='auswahl[]' value='".$daten[0]."'>

现在让我说我有一个功能(工人)

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()

我想通过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()的websockets)如何共存?更具体地说:我可以传递给工作人员的websocket是什么,以便他们可以使用它来发送消息上游?

换句话说,我应该如何创建上面的threading

0 个答案:

没有答案