【问题标题】:Non-blocking socket connect()'s within asyncioasyncio 中的非阻塞套接字 connect()
【发布时间】:2018-09-29 14:05:46
【问题描述】:

Here 是一个如何在asyncore 中进行非阻塞套接字连接(作为客户端)的示例。由于此模块已被推荐'Deprecated since version 3.6: Please use asyncio instead.' 弃用,它如何在asyncio 中实现?创建套接字并在协程中进行连接正在同步工作,并会产生链接问题中描述的问题。

【问题讨论】:

    标签: python-asyncio


    【解决方案1】:

    协程内的连接看起来与该协程同步,但实际上与事件循环相比是异步的。这意味着您可以创建任意数量的协程并行工作,而不会相互阻塞,而且所有协程都在单个线程中运行。

    如果您使用的是 http,请查看使用 aiohttp 的并行下载的 examples。如果您需要低级 TCP 连接,请查看 the documentation 中的示例并使用 asyncio.gather 并行运行它们:

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

    【讨论】:

    • 太好了,正是我需要的。我用这个,在协程末尾添加w.close()
    • @Vova 谢谢,我现在添加了缺少的close()(以及缺少的await 以启动)。
    猜你喜欢
    • 1970-01-01
    • 2010-10-31
    • 2013-10-15
    • 1970-01-01
    • 2012-01-05
    • 1970-01-01
    • 2013-06-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多