本文翻譯自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())