Answer the question
In order to leave comments, you need to log in
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:
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()
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question