Non-blocking socket connect()'s within asyncio

蓝咒 提交于 2020-06-13 09:09:02

问题


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.


回答1:


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", ...])


来源:https://stackoverflow.com/questions/52569118/non-blocking-socket-connects-within-asyncio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!