且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么我不能在协程调用的协程中发送 websocket?

更新时间:2023-01-05 08:14:17

可以将 websocket 作为参数传递.这里的问题是在等待 send 协程时 websocket 连接已经关闭(如您的错误消息中所述).这是因为连接上下文在 send_messages 任务可以发送消息之前完成.

It is fine to pass the websocket as an argument. The problem here is that the websocket connection is already closed when the send coroutine is awaited (as explained in your error message). That happens because the connection context finishes before the send_messages task can send the message.

相反,请考虑以下工作示例:

Instead, consider this working example:

async def main():
    async with websockets.connect('ws:/ip.address:port') as ws:
        await send_messages(ws)

async def send_messages(ws):
    await ws.send('TEST MESSAGE')


loop = asyncio.get_event_loop()
loop.run_until_complete(main)