本文翻译自python3.7官方文档——asyncio-stream,译者马鸣谦,邮箱 1612557569@qq.com。转载请注明出处。html
数据流(Streams)是用于处理网络链接
的高阶异步/等待就绪(async/await-ready)
原语,能够在不使用回调和底层传输协议的状况下发送和接收数据。
如下是一个用asyncio实现的TCP回显客户端:python
import asyncio async def tcp_echo_client(message): reader, writer = await asyncio.open_connection( '127.0.0.1', 8888) print(f'Send: {message!r}') writer.write(message.encode()) data = await reader.read(100) print(f'Received: {data.decode()!r}') print('Close the connection') writer.close() await writer.wait_closed() asyncio.run(tcp_echo_client('Hello World!'))
完整代码见例子一节。git
如下所列的高层asyncio方法能够被用做建立和处理Stream:github
reader
和writer
对象是StreamReader
和StreamWriter
类的实例。loop
是可选参数,在此方法被某个协程await
时可以自动肯定。limit
限定返回的StreamReader
实例使用的缓冲区
大小。默认状况下,缓冲区限制为64KiB
。loop.create_connection()
。ssl_handshake_timeout
参数。client_connected_cb
指定的回调函数,在新链接创建的时候被调用。该回调函数接收StreamReader
和StreamWriter
类的‘实例对’(reader,writer)
做为两个参数。client_connected_cb
能够是普通的可调用函数,也能够是协程函数。若是是协程函数,那么会被自动封装为Task
对象处理。loop
是可选参数,在此方法被某个协程await
时可以自动肯定。limit
限定返回的StreamReader
实例使用的缓冲区
大小。默认状况下,缓冲区限定值为64KiB
。loop.create_server()
。ssl_handshake_timeout
和start_serving
参数。(reader,writer)
对象。open_connection
相似,只是运行在Unix sockets上。loop.create_unix_connection()
ssl_handshake_timeout
参数。path
参数能够为类path(path-like)对象
start_server
,只是运行在Unix sockets上。loop.create_unix_server
ssl_handshake_timeout
参数。path
参数能够为类path(path-like)对象
定义一个读取器对象,提供从IO数据流中读取数据的API。
不建议 直接实例化StreamReader
对象。建议经过open_connection()
或start_server()
建立此类对象。网络
n
字节数据。若是n
未设置,或被设置为-1
,则读取至EOF
标志,并返回读到的全部字节。EOF
,则返回一个空的bytes
对象。\n
为标志)。\n
以前遇到EOF
,则返回已读取到的数据段。EOF
时内部缓冲区仍为空,则返回空的bytes
对象。n
字节数据。n
字节时遇到EOF
,则引起IncompleteReadError
异常。已经读取的部分数据能够经过IncompleteReadError.partial
属性获取。separator
。LimitOverrunError
,数据会被留在内部缓冲区中,能够被再次读取。separator
分隔符以前遇到EOF
,则引起IncompleteReadError
异常,内部缓冲区会被重置。IncompleteReadError.partial
属性会包含部分separator
。feed_eof()
被调用,则返回True
。定义一个写入器对象,提供向IO数据流中写入数据的API。
不建议直接实例化StreamWriter
对象,建议经过open_connection
或start_server
实例化对象。异步
write_eof
方法,则返回True
,不然返回False
。write()
应同drain()
一同使用。bytes
列表(或任何的可迭代对象)。drain()
一同使用。writer.write(data) await writer.drain()
drain()
阻塞,待到缓冲区回落到下限时,写操做能够被恢复。当不须要等待时,drain()
会当即返回。True
。close()
后调用此方法。import asyncio async def tcp_echo_client(message): reader, writer = await asyncio.open_connection( '127.0.0.1', 8888) print(f'Send: {message!r}') writer.write(message.encode()) data = await reader.read(100) print(f'Received: {data.decode()!r}') print('Close the connection') writer.close() asyncio.run(tcp_echo_client('Hello World!'))
import asyncio async def handle_echo(reader, writer): data = await reader.read(100) message = data.decode() addr = writer.get_extra_info('peername') print(f"Received {message!r} from {addr!r}") print(f"Send: {message!r}") writer.write(data) await writer.drain() print("Close the connection") writer.close() async def main(): server = await asyncio.start_server( handle_echo, '127.0.0.1', 8888) addr = server.sockets[0].getsockname() print(f'Serving on {addr}') async with server: await server.serve_forever() asyncio.run(main())
import asyncio import urllib.parse import sys async def print_http_headers(url): url = urllib.parse.urlsplit(url) if url.scheme == 'https': reader, writer = await asyncio.open_connection( url.hostname, 443, ssl=True) else: reader, writer = await asyncio.open_connection( url.hostname, 80) query = ( f"HEAD {url.path or '/'} HTTP/1.0\r\n" f"Host: {url.hostname}\r\n" f"\r\n" ) writer.write(query.encode('latin-1')) while True: line = await reader.readline() if not line: break line = line.decode('latin1').rstrip() if line: print(f'HTTP header> {line}') # Ignore the body, close the socket writer.close() url = sys.argv[1] asyncio.run(print_http_headers(url))
用法:socket
python example.py http://example.com/path/page.html
或:async
python example.py https://example.com/path/page.html
import asyncio import socket async def wait_for_data(): # Get a reference to the current event loop because # we want to access low-level APIs. loop = asyncio.get_running_loop() # Create a pair of connected sockets. rsock, wsock = socket.socketpair() # Register the open socket to wait for data. reader, writer = await asyncio.open_connection(sock=rsock) # Simulate the reception of data from the network loop.call_soon(wsock.send, 'abc'.encode()) # Wait for data data = await reader.read(100) # Got data, we are done: close the socket print("Received:", data.decode()) writer.close() # Close the second socket wsock.close() asyncio.run(wait_for_data())