K
K
kratorr2018-06-13 10:09:14
Python
kratorr, 2018-06-13 10:09:14

How to do a reconnect in asyncio?

There is something like this code:

import asyncio


class ClientProtocol(asyncio.Protocol):
    def __init__(self, loop):
        self.loop = loop
        
    def connection_made(self, transport):
        self.transport = transport
     
    def data_received(self, data):
        _process_command(self.data)
    
    def _process_command(self, data):
        if "connection" in data:
            self.foo(data)
        elif 'reconnect' in data:
           #реконнект
        elif "exit" in data:
            self.bar()
 
    def foo(self, data):
        pass
    
    def bar(self):
        pass
    
if __name__ ==  "__main__":
    loop = asyncio.get_event_loop()
    coros = [
        loop.create_connection(lambda: ClientProtocol(loop), '10.10.10.1', 666),
        loop.create_connection(lambda: ClientProtocol(loop), '10.10.10.2', 666),
        loop.create_connection(lambda: ClientProtocol(loop), '10.10.10.3', 666)
    ]
    loop.run_until_complete(asyncio.gather(*coros))
    loop.run_forever()
    loop.close()

Tell me how to reconnect when a command is received or when an unsuccessful connection attempt is made?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question