Skip to content Skip to sidebar Skip to footer

Why Can't I Send Down A Websocket In A Coroutine Called By A Coroutine?

Why does: async def setup(): async with websockets.connect('ws:/ip.address:port') as ws: await ws.send('TEST MESSAGE') def startup(): loop = asyncio.new_event_loop

Solution 1:

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:

asyncdefmain():
    asyncwith websockets.connect('ws:/ip.address:port') as ws:
        await send_messages(ws)

asyncdefsend_messages(ws):
    await ws.send('TEST MESSAGE')


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

Post a Comment for "Why Can't I Send Down A Websocket In A Coroutine Called By A Coroutine?"