Skip to content Skip to sidebar Skip to footer

Multiple Websocket Streaming With Asyncio/aiohttp

I am trying to subscribe to multiple Websocket streaming using python's asyncio and aiohttp. When I run the below code, it only prints 'a' but nothing else in the console as output

Solution 1:

You incorrectly invoke ws_connect. Right way:

asyncwith aiohttp.ClientSession() as session:
    asyncwith session.ws_connect('url') as was:
        ...

Full example:

import aiohttp
import asyncio

asyncdefcoro(event, item1, item2):
    print("a")
    asyncwith aiohttp.ClientSession() as session:
        asyncwith session.ws_connect('wss://echo.websocket.org') as ws:
            event.set()
            print("b")
            await asyncio.gather(ws.send_json(item1),
                                 ws.send_json(item2))
            asyncfor msg in ws:
                print("c")
                print(msg)


asyncdefws_connect(item1, item2):
    event = asyncio.Event()
    task = asyncio.create_task(coro(event, item1, item2))
    await event.wait()  # wait until the event is set() to True, while waiting, blockreturn task

asyncdefmain():
    item1 = {
        "method": "subscribe",
        "params": {'channel': "bar"}
    }
    item2 = {
        "method": "subscribe",
        "params": {'channel': "foo"}
    }
    ws_task = await ws_connect(item1, item2)
    await ws_task

asyncio.run(main())

Post a Comment for "Multiple Websocket Streaming With Asyncio/aiohttp"