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:
async with aiohttp.ClientSession() as session:
async with session.ws_connect('url') as was:
...
Full example:
import aiohttp
import asyncio
async def coro(event, item1, item2):
print("a")
async with aiohttp.ClientSession() as session:
async with session.ws_connect('wss://echo.websocket.org') as ws:
event.set()
print("b")
await asyncio.gather(ws.send_json(item1),
ws.send_json(item2))
async for msg in ws:
print("c")
print(msg)
async def ws_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, block
return task
async def main():
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"