我正在 python 中使用 asyncio 编写程序,其中客户端连接到服务器,它们交换一些消息,服务器关闭连接。 我还需要实现一个重试机制,如果服务器宕机,客户端将每 5 秒尝试重新连接一次。
作为 Python 新手和一般的 asyncio 概念,我需要帮助来理解如何实现它。 下面是我的代码片段,我开始与服务器建立连接,并在服务器端套接字关闭的情况下处理它。
async def main():
# Get a reference to the event loop as we plan to use
# low-level APIs.
format = "%(asctime)s: %(message)s"
logging.basicConfig(format=format, level=logging.INFO,
datefmt="%H:%M:%S")
executor1 = concurrent.futures.ThreadPoolExecutor(max_workers=2)
future1 = executor1.submit(init_thread)
loop = asyncio.get_running_loop()
on_con_lost = loop.create_future()
message = future1.result()
message = struct.pack(">I", len(message)) + bytes(message, "utf-8")
transport, protocol = await loop.create_connection(
lambda: EchoClientProtocol(message, on_con_lost),
'127.0.0.1', 9000)
# Wait until the protocol signals that the connection
# is lost and close the transport.
try:
await on_con_lost
finally:
transport.close()
asyncio.run(main())