源代码: Lib/asyncio/streams.py


流是操控网络连接的高级 async/await 就绪原语。流允许发送和接收数据,在不使用回调 (或低级协议) 和传输的情况下。

这里是使用 asyncio 流编写的 TCP 回显客户端范例:

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())
    await writer.drain()
    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!'))