Asyncio流即使运行了writer.close(),也会自动重新启动以读取数据。
创始人
2024-09-21 06:30:35
0

在使用 Asyncio 流时,关闭写入器(writer)可能无法立即停止读取器(reader)的操作。这会导致读取器继续运行,即使写入器已经关闭。为了更好地控制延迟和数据流,可以使用异步 with 语句来确保在关闭写入器后读取器也会被关闭。

以下是一个代码示例:

import asyncio

async def read_data(stream): data = await stream.read(1024) print(f"Read {len(data)} bytes of data") return data

async def main(): # Create a server socket server = await asyncio.start_server(handle_connection, 'localhost', 8888)

# Wait for a connection
async with server:
    await server.serve_forever()

async def handle_connection(reader, writer): while True: # Read data from the stream data = await read_data(reader)

    # Process the data
    print(f"Processing {len(data)} bytes of data")

    # If the writer is closed, exit the loop
    if writer.is_closing():
        break

# Close the stream when finished reading
writer.close()
await writer.wait_closed()

Start the event loop

asyncio.run(main())

在上面的代码示例中,使用异步 with 语句确保在关闭写入器后读取器也会被关闭。通过调用writer.wait_closed(),我们等待所有数据都被读取后再关闭读取器。这可以确保没有数据被丢失并且所有读取操作都在关闭读取器前完成。

相关内容

热门资讯

线上(wepoke真的)原来是... 线上(wepoke真的)原来是真的有挂!其实真的有挂(2022已更新)(哔哩哔哩);亲,其实确实真的...
两教程(Wepoke程序)软件... 两教程(Wepoke程序)软件透明挂辅助工具(软件透明挂)透视辅助(2024已更新)(哔哩哔哩);致...
软件(wepoke透明)原来是... 软件(wepoke透明)原来是真的有挂!其实真的有挂(2020已更新)(哔哩哔哩)是一款可以让一直输...
一模拟器(德扑工具)外挂辅助工... 一模拟器(德扑工具)外挂辅助工具(透视)透视辅助(2025已更新)(哔哩哔哩);亲真的是有正版授权,...
系统(aapoker讲解)竟然... 系统(aapoker讲解)竟然真的有挂!其实真的有挂(2021已更新)(哔哩哔哩);aapoker讲...
6系统(aapoker下载)外... 6系统(aapoker下载)外挂辅助工具(辅助挂)透视辅助(2023已更新)(哔哩哔哩)aapoke...
智能(德扑之星刷数据)果真真的... 智能(德扑之星刷数据)果真真的有挂!原来真的有挂(2025已更新)(哔哩哔哩);《WPK辅助透视》‌...
1机器人(德州nzt软件)软件... 1机器人(德州nzt软件)软件透明挂辅助软件(透视)透视辅助(2022已更新)(哔哩哔哩);人气非常...
ai代打(德扑之星决策)确实是... ai代打(德扑之星决策)确实是真的有挂!原来真的有挂(2020已更新)(哔哩哔哩);科技详细教程小薇...
第8透明(wepoke数据)外... 第8透明(wepoke数据)外挂透明挂辅助神器(辅助挂)透视辅助(2023已更新)(哔哩哔哩);原来...