X
X
Xymis2021-07-22 19:25:15
Python
Xymis, 2021-07-22 19:25:15

How to implement an asynchronous client with two coroutines?

Hello!
There is no way to implement the following idea:
There are two coroutines
1. Waits for a message from the server and prints the response

async def handler(ws):
        response = await ws.recv()
        print(response)


2. Pings the server every 3 seconds

async def ping(ws):
        await asyncio.sleep(3)
        await ws.send(b'ping')


async def main():

    loop = asyncio.new_event_loop()

    async with websockets.connect('ws://127.0.0.1:8080/ws') as ws:
        await ws.send('hello'.encode())

        while True:
            await handler(ws)
            await ping(ws)

asyncio.run(main())


The implementation problem is that ping takes all control, and when I send messages to the handler, they do not process them until asyncio.sleep is completed inside ping . Tell me

how to properly implement such logic. Thanks in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2021-07-22
@Xymis

https://docs.python.org/3/library/asyncio-task.htm...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question