异步内的非阻塞套接字连接() [英] Non-blocking socket connect()'s within asyncio
本文介绍了异步内的非阻塞套接字连接()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Here是如何在asyncore
内进行非阻塞套接字连接(作为客户端)的示例。由于推荐'Deprecated since version 3.6: Please use asyncio instead.'
此模块已弃用,因此如何在asyncio
中实现此功能?在协程中创建套接字及其连接是同步工作的,并且会产生问题,如链接问题中所述。
推荐答案
协同例程内连接看似与协同例程同步,但实际上相对于事件循环是异步的。这意味着您可以创建任意数量的并行工作的协程,而不会相互阻塞,但所有协程都在单个线程内运行。
如果您使用的是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", ...])
这篇关于异步内的非阻塞套接字连接()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文