首页 > 解决方案 > python asyncio通过回调函数获取数据

问题描述

我有一个第三方代码向我发送数据(不一定在当前循环中),我使用我提供的回调方法获得这些数据,我希望我的 websocket 初始化第三个 patry 实例一次并发送我从中获得的所有内容(ws.send )。

如果我使用执行器,它可以工作,但它会阻止我获得多个连接。

不起作用的示例代码:

async def callback(ws, event_type, message):
    await ws.send(message)

async def producer(ws):
    func = functools.partial(callback, ws, event_type)
    ThirdPartyCode.enable(func)
    while True:
        await asyncio.sleep(0.2)

def main():
    start_server = websockets.serve(producer, 'localhost', PORT)

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

标签: pythonwebsocketpython-asyncio

解决方案


推荐阅读