1. 异步流
asyncio 的一个主要好处是能够使用非阻塞流。
Asyncio 提供非阻塞 I/O 套接字编程。这是通过流提供的。
可以打开提供对流写入器和流写入器的访问的套接字。在合适的时候,使用协同程序可以从流中写入和读取数据并暂停。完成后,可以关闭套接字。
异步流功能是低级的,这意味着必须手动实现所需的任何协议。
这可能包括常见的 Web 协议,例如:
用于与 Web 服务器交互的 HTTP 或 HTTPS
用于与电子邮件服务器交互的 SMTP
用于与文件服务器交互的 FTP。
这些流还可用于创建服务器以使用标准协议处理请求,或开发您自己的特定于应用程序的协议。
现在我们知道什么是异步流,让我们看看如何使用它们。
2. 如何打开连接
可以使用 asyncio.open_connection() 函数打开 asyncio TCP 客户端套接字连接。
这是一个必须等待的协程,一旦套接字连接打开就会返回。
该函数返回用于与套接字交互的 StreamReader 和 StreamWriter 对象。
... # open a connection reader, writer = await asyncio.open_connection(...)
There are multiple parameters that can be used to configure the socket connection in the asyncio.open_connection() function.。两个必需的参数是主机和端口。
host 是一个字符串,指定要连接的服务器,例如域名或 IP 地址。
port为socket端口号,如HTTP服务器为80,HTTPS服务器为443,SMTP为23等。
... # open a connection to an http server reader, writer = await asyncio.open_connection('www.google.com', 80)
通过 SSL 协议支持加密套接字连接。最常见的例子可能是正在取代 HTTP 的 HTTPS。这可以通过将“ssl”参数设置为 True 来实现。
... # open a connection to an https server reader, writer = await asyncio.open_connection('www.google.com', 443, ssl=True)
3. 如何启动服务器
可以使用 asyncio.start_server() 函数打开 asyncio TCP 服务器套接字。这是一个必须等待的协程。
该函数返回一个代表正在运行的服务器的 asyncio.Server 对象。
... # start a tcp server server = await asyncio.start_server(...)
三个必需的参数是回调函数、主机和端口。当客户端连接到服务器时,回调函数会被调用,它是一个有名称的自定义函数。
主机是客户端将指定连接的域名或 IP 地址。FTP使用的端口是21,HTTP使用的端口是80。这些端口是用于接收连接的套接字端口号。
# handle connections async def handler(reader, writer): # ... ... # start a server to receive http connections server = await asyncio.start_server(handler, '127.0.0.1', 80)
4. 如何使用 StreamWriter 写入数据
可以借助 asyncio.StreamWriter 将数据传输到套接字。数据以字节形式写入。可以使用 write() 方法将字节数据写入套接字。
... # write byte data writer.write(byte_data)
或者,可以使用 writelines() 方法写入组织成列表或可迭代的多“行”字节数据。
... # write lines of byte data writer.writelines(byte_lines)
写入数据块或挂起调用协程的方法都没有。写入字节数据后,最好通过 drain() 方法清空套接字。这是一个协程,会使呼叫者暂停,直到数据传输并且插座就绪。
... # write byte data writer.write(byte_data) # wait for data to be transmitted await writer.drain()
5. 如何使用 StreamReader 读取数据
使用 asyncio.StreamReader 可以读取套接字中的数据。数据以字节格式读取,因此字符串在使用前可能需要进行编码。所有读取方法都是必须等待的协程。
可以通过 read() 方法读取任意数量的字节,该方法将一直读取到文件末尾 (EOF)。
... # read byte data byte_data = await reader.read()
此外,可以通过“n”参数指定要读取的字节数。如果您知道下一个响应的预期字节数,这可能会有所帮助。
... # read byte data byte_data = await reader.read(n=100)
可以使用 readline() 方法读取单行数据。这将返回字节,直到遇到换行符“\n”或 EOF。
这在阅读使用文本行操作的标准协议时很有用。
... # read a line data byte_line = await reader.readline()
此外,还有一个 readexactly() 方法来读取确切数量的字节,否则会引发异常,还有一个 readuntil() 方法将读取字节,直到读取字节形式的指定字符。
6. 如何关闭连接
可以使用 asyncio.StreamWriter 对象关闭网络套接字。可以调用 close() 方法来关闭套接字。此方法不会阻塞。
... # close the socket writer.close()
尽管 close() 方法是非阻塞的,我们可以等待套接字完全关闭后再继续。这可以通过 wait_closed() 方法来实现。这是一个可以等待的协程。
... # close the socket writer.close() # wait for the socket to close await writer.wait_closed()
我们可以通过 is_closing() 方法检查套接字是否已经关闭或正在关闭。
... # check if the socket is closed or closing if writer.is_closing(): # ...
以上是Python异步之非阻塞流如何使用的详细内容。更多信息请关注PHP中文网其他相关文章!

pythonuseshybridapprace,ComminingCompilationTobyTecoDeAndInterpretation.1)codeiscompiledtoplatform-Indepententbybytecode.2)bytecodeisisterpretedbybythepbybythepythonvirtualmachine,增强效率和通用性。

theKeyDifferencesBetnewpython's“ for”和“ for”和“ loopsare:1)” for“ loopsareIdealForiteringSequenceSquencesSorkNowniterations,而2)”,而“ loopsareBetterforConterContinuingUntilacTientInditionIntionismetismetistismetistwithOutpredefinedInedIterations.un

在Python中,可以通过多种方法连接列表并管理重复元素:1)使用 运算符或extend()方法可以保留所有重复元素;2)转换为集合再转回列表可以去除所有重复元素,但会丢失原有顺序;3)使用循环或列表推导式结合集合可以去除重复元素并保持原有顺序。

fasteStmethodMethodMethodConcatenationInpythondependersonListsize:1)forsmalllists,operatorseffited.2)forlargerlists,list.extend.extend()orlistComprechensionfaster,withextendEffaster,withExtendEffers,withextend()withextend()是extextend()asmoremory-ememory-emmoremory-emmoremory-emmodifyinginglistsin-place-place-place。

toInSerteLementIntoApythonList,useAppend()toaddtotheend,insert()foreSpificPosition,andextend()formultiplelements.1)useappend()foraddingsingleitemstotheend.2)useAddingsingLeitemStotheend.2)useeapecificindex,toadapecificindex,toadaSpecificIndex,toadaSpecificIndex,blyit'ssssssslorist.3 toaddextext.3

pythonlistsareimplementedasdynamicarrays,notlinkedlists.1)他们areStoredIncoNtiguulMemoryBlocks,mayrequireRealLealLocationWhenAppendingItems,EmpactingPerformance.2)LinkesedlistSwoldOfferefeRefeRefeRefeRefficeInsertions/DeletionsButslowerIndexeDexedAccess,Lestpypytypypytypypytypy

pythonoffersFourmainMethodStoreMoveElement Fromalist:1)删除(值)emovesthefirstoccurrenceofavalue,2)pop(index)emovesanderturnsanelementataSpecifiedIndex,3)delstatementremoveselemsbybybyselementbybyindexorslicebybyindexorslice,and 4)

toresolvea“ dermissionded”错误Whenrunningascript,跟随台词:1)CheckAndAdjustTheScript'Spermissions ofchmod xmyscript.shtomakeitexecutable.2)nesureThEseRethEserethescriptistriptocriptibationalocatiforecationAdirectorywherewhereyOuhaveWritePerMissionsyOuhaveWritePermissionsyYouHaveWritePermissions,susteSyAsyOURHomeRecretectory。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

Dreamweaver CS6
视觉化网页开发工具

PhpStorm Mac 版本
最新(2018.2.1 )专业的PHP集成开发工具

SecLists
SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

MinGW - 适用于 Windows 的极简 GNU
这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。