首页 > 解决方案 > 如何使用 Jupyter 笔记本连接多个 websocket

问题描述

Jupyter notebook 上的这个程序只与第一个 websocket 连接。怎么了?

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)

标签: websocketjupyter-notebookpython-asyncioaiohttp

解决方案


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))

推荐阅读