I am writing a program using asyncio in python where a Client connects to a server, they exchange some messages and the Server closes the connection.
What I also need to implement is a retry mechanism, where in case the server is down the client will keep trying to reconnect every 5 seconds.
Being new in python and with the asyncio concept in general, I need help to understand how to implement that.
Below is a snippet of my code where I start the connection with the server and where I handle it in case of socket closure on server side.
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())
question from:
https://stackoverflow.com/questions/65903187/tcp-client-reconnect-to-server-if-the-server-is-down-using-asyncio 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…