gpt4 book ai didi

Python websockets 服务器和 websockets 客户端在运行两个任务时使用 asyncio 断言错误

转载 作者:行者123 更新时间:2023-12-04 09:34:12 43 4
gpt4 key购买 nike

我有 3 台机器; A、B、C。

A 正在运行 C 想要连接的 websocket 服务器,但 C 无法直接连接到 A。为了解决这个问题,我想通过机器 B 本质上“代理”websocket。

A 充当发布者并每隔几秒生成新的数据包,我想将其推送给 C。C 不需要向 A 发送任何内容(尽管将来可能需要)。

我想通过使用 websockets ( https://pypi.org/project/websockets/ ) 模块来实现这个代理。我目前正在尝试在 B 上创建一个服务器,用于监听连接并与任何客户端保持 websocket 连接。然后我想异步运行一个连接到机器 A 的 websocket 客户端。这是一个订阅者连接,从 websocket 连接到 A 的任何更新都应该推送到 C(或连接到 B 的任何其他客户端)。

这是我当前的(最小)实现,其中发生错误。

sockets = set()

def register(websocket):
sockets.add(websocket)

def unregister(websocket):
sockets.remove(websocket)

async def update_clients(update):
if sockets:
await asyncio.wait([socket.send(update) for socket in sockets])

async def client_server(websocket, path):
register(websocket)
await websocket.send("Welcome!")

async def live_updates():
async with websockets.connect(LIVE_URL) as websocket:
async for update in websocket.recv():
await update_clients(update)

webserver = websockets.serve(client_server, "0.0.0.0", PORT)

loop = asyncio.get_event_loop()
loop.run_until_complete(webserver)
loop.run_until_complete(live_updates)
loop.run_forever()

错误如下

Traceback (most recent call last):
File "/usr/lib/python3.6/asyncio/base_events.py", line 1310, in call_exception_handler
self.default_exception_handler(context)
File "/usr/lib/python3.6/asyncio/base_events.py", line 1282, in default_exception_handler
value = repr(value)
File "/usr/lib/python3.6/asyncio/base_tasks.py", line 15, in _task_repr_info
coro = coroutines._format_coroutine(task._coro)
File "/usr/lib/python3.6/asyncio/coroutines.py", line 276, in _format_coroutine
assert iscoroutine(coro)
AssertionError

最佳答案

当我删除第二个 run_until_complete(live_updates) 时,代码运行没有错误。所以我删除了第一个 run_until_complete,将我的代码与 https://websockets.readthedocs.io/en/stable/intro.html 中的示例代码进行了比较并意识到

run_until_complete(live_updates) 应该是 run_until_complete(live_updates())

我留下这个问题是为了防止有人遇到同样的错误,因为错误消息会让初学者感到困惑。

关于Python websockets 服务器和 websockets 客户端在运行两个任务时使用 asyncio 断言错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62673663/

43 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com