websocket - 如何使用 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)
解决方案
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))
推荐阅读
- c# - 如何在 asp.net core 2.1 中部署 secrets.json
- dynamics-crm - 统一客户端界面中的 Dynamics 365(9.0) - 如何在新建按钮和可编辑表单上方启用网格?
- unity3d - Visual Studio for Mac 统一执行失败
- reactjs - 操作必须是使用 Redux Thunk 的普通对象错误
- python - 如何在 Python 中对列表中的单词进行编码
- c++ - 2 个移位图像与 OpenCV 的 C++ 互相关
- ruby-on-rails - 当用户取消选择所有选项时,存储的值未设置为 nil - rails / simple_form
- python - 如何区分 Vim 语法中的 Python 单行字符串和多行字符串?
- python - 如何更改字典中的列表?
- d3.js - 为 D3 SVG 节点添加标签和添加图标