【发布时间】:2021-01-02 08:12:24
【问题描述】:
这可能是一个愚蠢的问题,但我遗漏了一些我认为可能很明显的东西:
我正在使用 Python 3.8 异步流:
import asyncio
async def client_handler():
reader, writer = await asyncio.open_connection('127.0.0.1', 9128)
server_name = writer.get_extra_info('peername')[0]
print(f"Connecting to: { server_name }")
data = b''
close_client = False
try:
while not close_client:
print(data)
data = await reader.read(1024)
print(data)
if data != b'':
print(data.decode('utf-8'))
data = b''
writer.close()
except:
pass
finally:
writer.close()
await writer.wait_closed()
asyncio.run(client_handler())
我想我预计它会尝试读取 1024 字节,但如果那里什么都没有,那么它只会返回 None 或空字节字符串或其他东西,但它只是坐在那里直到接收到数据。
我是否误解了 read 应该做什么?是否可以使用另一种方法来查看缓冲区或轮询以查看是否有任何数据实际传入?
例如,假设我正在编写一个示例聊天程序服务器和客户端,它们需要能够同时动态发送和接收数据......我如何使用 asyncio 流实现它?我应该只构建自己的 asyncio.Protocol 子类吗?
【问题讨论】:
标签: python sockets stream python-asyncio