How to use ASYNCIO through multi python files?

Viewed 45

(I apologize for my English, I'm French ^^')

I stated with Asyncio method, and I have a little problem. I have 3 python files, main.py, commands.py and Client.py (all names are for examples), and I try to run multiple tasks, at the same time, in commands.py thought my main.py. But each task waits the previous task for started.

In Client.py (but not care, I simplify this, it's just for context)

class StartClient(threading.Thread):
    def __init__(self, port = 0):
        threading.Thread.__init__(self)
        self.setDaemon(True)
        self.port = port

    def get_name(self) :
        self.client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.client_socket.connect(("localhost", self.port))
        self.client_socket.setblocking(0)
        self.client_socket.sendall("get_name")
        reply = self.client_socket.recv(4098)
        print (f"reply from {self.port}: ", reply)
        return reply

In Commands.py

async def client_get_name(port):
    print (f"start_client {port}")
    client = StartClient(port)
    name = client.get_name()
    return name

async def run_mutl_clients():
    tasks = {}
    ports = [61,65,67]
    for port in ports:
        tasks[str(port)]= asyncio.create_task(client_get_name(port))
        
    for port, task in tasks.items() : 
        scene_name = await task
        opened_instances[str(port)] = scene_name
    

    MyPySideDialog.launch(opened_instances)

In my main.py

class FabulousPySideApp():
    def __init__(self):
    self.run_async()

    def run_async(self): 
        asyncio.run(Commands.run_mutl_clients())

So, I wish to start multiple client_get_name() at the same time (one by ports), and waiting they are finished to send opened_instances to MyPySideDialog (this just an ui for users, just no care about that). StartClient() is a function who started a socket client (by type, by port). This is a bit too long if I have many ports to open, one by one. I want to start all ports in the same time, waiting their answers. Expected :

>>start_client 61
>>start_client 65
>>start_client 67
>>reply from 61, "name1"
>>reply from 65, "name2"
>>reply from 67, "name3"
[Finished in 2s]

Reality :

>>start_client 61
>>reply from 61, "name1"
>>start_client 65
>>reply from 65, "name2"
>>start_client 67
>>reply from 67, "name3
[Finished in 6s]
"

I think, I was missed some things... Someone can help me :)

Thanks

0 Answers
Related