首页 > 解决方案 > 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)

标签: pythonpython-asyncioaiohttp

解决方案


推荐阅读