Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
469 views
in Technique[技术] by (71.8m points)

python - TCP client reconnect to server if the server is down (using Asyncio)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...