面试题答案
一键面试- 使用
asyncio
实现连接超时机制的描述:- 在
asyncio
中,可以使用asyncio.wait_for
函数来设置连接操作的超时时间。asyncio.wait_for
接受两个参数,第一个是一个awaitable
对象(在这里就是连接操作的awaitable
),第二个是超时时间(以秒为单位)。如果在指定的超时时间内awaitable
对象没有完成,asyncio.wait_for
会引发TimeoutError
异常。
- 在
- 关键代码示例:
import asyncio
async def tcp_client():
try:
# 尝试连接服务器,设置超时时间为5秒
reader, writer = await asyncio.wait_for(asyncio.open_connection('127.0.0.1', 8888), timeout = 5)
writer.write(b'Hello, server!')
await writer.drain()
data = await reader.read(100)
print(f"Received: {data.decode()}")
writer.close()
await writer.wait_closed()
except TimeoutError:
print("Connection timed out")
if __name__ == '__main__':
asyncio.run(tcp_client())
上述代码中,asyncio.wait_for
函数将asyncio.open_connection
操作限制在5秒内完成。如果连接操作超过5秒未完成,就会捕获TimeoutError
异常并打印“Connection timed out”。