0

Here is an example how to do non-blocking socket connects (as client) within asyncore. Since this module is deprecated with recomendation 'Deprecated since version 3.6: Please use asyncio instead.' How does it possible within asyncio? Creating socket and it's connect inside coroutine is working syncronious and create problem like it described in linked question.

Vova
  • 563
  • 8
  • 20

1 Answers1

0

A connect inside a coroutine appears synchronous to that coroutine, but is in fact asynchronous with respect to the event loop. This means that you can create any number of coroutines working in parallel without blocking each other, and yet all running inside a single thread.

If you are doing http, look at examples of parallel downloads using aiohttp. If you need low-level TCP connections, look at the examples in the documentation and use asyncio.gather to run them in parallel:

async def talk(host):
    # wait until connection is established, but without blocking
    # other coroutines
    r, w = await asyncio.open_connection(host, 80)
    # use the streams r, w to talk to the server - for example, echo:
    while True:
        line = await r.readline()
        if not line:
            break
        w.write(line)
    w.close()

async def talk_many(hosts):
    coros = [talk(host) for host in hosts]
    await asyncio.gather(*coros)

asyncio.run(talk_many(["host1", "host2", ...])
user4815162342
  • 141,790
  • 18
  • 296
  • 355