是否有使用asyncio轮询间歇性服务器的标准模式?
采用以下示例:从不可靠的TCP服务器读取每秒的客户端。没有错误处理,async/await
符号看起来很棒:
class BasicTCPClient(object):
"""TCP client without error handling."""
def __init__(self, ip, port):
self.ip = ip
self.port = port
async def connect(self):
reader, writer = await asyncio.open_connection(self.ip, self.port)
self.connection = {'reader': reader, 'writer': writer}
async def get(self, request):
self.connection['writer'].write(request.encode())
return await self.connection['reader'].readuntil(b'\n')
async def read():
client = BasicTCPClient('ip', 8000)
await client.connect()
while True:
print(await client.get('request'))
await asyncio.sleep(1)
ioloop = asyncio.get_event_loop()
try:
ioloop.run_until_complete(read())
except KeyboardInterrupt:
pass
但这并不能很好地处理断开连接/重新连接。我有一个有效的解决方案,但它接近100 LOC并否定了async/await
的所有优雅。