首页 > 解决方案 > 如何使用 asyncio.Protocol 处理断开/重新连接?

问题描述

我正在尝试设置一个将 2 个连接“粘合”在一起的应用程序。我正在尝试正确使用异步的东西。

到目前为止,我是这样做的:

import asyncio

class Protocol1(asyncio.Protocol):
    def connection_lost(self, exc):
        # should I do something here?
    # some stuff

class Protocol2(asyncio.Protocol):
    # some other stuff

async def main():
    loop = asyncio.get_running_loop()
    transport1, protocol1 = await loop.create_unix_connection(lambda: Protocol1(), path=SOCKET_PATH)

    on_con_lost = loop.create_future()  # is this sound?

    transport2, protocol2 = await loop.create_connection(lambda: Protocol2(), host=HOST, port=PORT)

    protocol2.procotol1 = protocol1  # maybe this is ugly too?
    await on_con_lost
    print("Both connection lost?")

asyncio.run(main())

我想了解如何处理重新连接,以防两个连接之一出现故障。你能指出我正确的方向吗?

标签: pythonpython-asyncio

解决方案


推荐阅读