如何用Jupyter笔记本连接多用web套接字。

问题描述 投票:0回答:1

这个程序在Jupyter笔记本上只与第一个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)
websocket jupyter-notebook python-asyncio aiohttp
1个回答
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))
© www.soinside.com 2019 - 2024. All rights reserved.