0

This program on Jupyter notebook connect only with first websocket. What is wrong?

session1 = aiohttp.ClientSession()
session2 = aiohttp.ClientSession() 

async with session1.ws_connect('host1') as ws1:
    async for msg1 in ws1:
        print(msg1.data)
        await asyncio.sleep(5)

async with session2.ws_connect('host2') as ws2:
    async for msg2 in ws2:
        print(msg2.data)
        await asyncio.sleep(5)
kigudesm
  • 1
  • 1
  • Can you add more context/code? It's a bit unclear what you're trying to achieve. – Charming Robot May 31 '20 at 18:54
  • I want to get prices from three different exchanges using websockets and in case of achiving some limits I will post tickets to these exchanges. But I don't know how to start to get information from three websockets concurrently because the first loop don't allow to start another loops and actions. – kigudesm Jun 01 '20 at 15:33
  • You can use the `asyncio.gather` API. Just wrap each of these `ws_connect` commands in a separate coroutine. Then call `asyncio.gather` on them. – Charming Robot Jun 01 '20 at 15:44

1 Answers1

0
import asyncio
import aiohttp

urls = [host1, host2, ...]
async def websocket(url):
    session = aiohttp.ClientSession()
    async with session.ws_connect(url) as ws:
        async for msg in ws:
            print(msg.data)
loop = asyncio.get_event_loop()
tasks = [websocket(url) for url in urls]
loop.run_until_complete(asyncio.wait(tasks))
kigudesm
  • 1
  • 1