与不可靠的服务器进行Pythonic asyncio通信

时间:2017-09-11 21:46:48

标签: python python-3.5 python-3.6 python-asyncio

是否有使用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的所有优雅。

0 个答案:

没有答案