K
K
kratorr2018-05-24 12:24:40
Python
kratorr, 2018-05-24 12:24:40

How to stop a coroutine from running?

Good afternoon, I am writing a client application to communicate with multiple devices. Taking an example from the documentation for asyncio, I threw in a client, everything works fine with several dozen devices, but I can’t figure out how to stop clients from working after receiving the desired message. Here is an example code:

spoiler
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 "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()

The handler, in the presence of "exit", launches the bar () function and in it somehow it is necessary to stop the work of this connection, after some time the "exit" command will come from all clients and the code should complete its work. Please tell me how to be in this situation.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Gornostaev, 2018-05-24
@sergey-gornostaev

self.transport.close()

V
Vladimir, 2018-05-24
@vintello

and also look at this example from the documentation,
I think you still need to implement connection_lost

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question