python - aiohttp websocket重新连接
问题描述
我有以下代码,它按预期工作,但是我不知道如何处理断开连接并自动重新连接 websocket 并重新启动 3 个任务。
最好的方法是什么?
import asyncio
import aiohttp
from aiohttp import web
async def producer(app):
while True:
message = await app['queue'].get()
await app['ws'].send(message)
async def heartbeat(app):
while True:
await asyncio.sleep(30)
await app['queue'].put("heartbeat")
async def consumer(app):
async for msg in app['ws']:
if msg.type == aiohttp.WSMsgType.TEXT:
if msg.data == 'close cmd':
await app['ws'].close()
break
else:
await app['ws'].send_str(msg.data + '/answer')
elif msg.type == aiohttp.WSMsgType.ERROR:
break
async def on_startup(app):
session = aiohttp.ClientSession()
app['queue'] = asyncio.Queue()
app['ws'] = await session.ws_connect('http://example.org/ws')
app['consumer'] = asyncio.create_task(consumer(app))
app['producer'] = asyncio.create_task(producer(app))
app['heartbeat'] = asyncio.create_task(heartbeat(app))
if __name__ == "__main__":
appli = web.Application()
appli.on_startup.append(on_startup)
web.run_app(appli, port=5000)
解决方案
推荐阅读
- gnuplot - gnuplot 中的自动偏移
- android - androidx 找不到符号 androidx.databinding.DataBindingComponent
- macos - 无法列出我的 Developer ID 应用程序身份
- sql - SQL 查询在高负载期间返回不正确的结果
- postgresql - 为什么 gorm postgresql 在“)”处或附近抛出 pq:语法错误?
- java - 为什么转储中有这么多 SessionFactoryImpl 对象?
- elisp - 需要扩展elisp函数
- excel - Excel 公式和条件格式:如何根据条件匹配另一个表中的当前单元格
- vulkan - 主机写保证源访问范围
- c# - 设置时间格式时出错,无法设置范围类的 numberformat 属性