使用asyncio的程序结构

时间:2014-12-26 13:58:39

标签: python python-3.x coroutine python-asyncio

我目前有一个这样的程序:

set_up_everthing()

while True:
    if new_client_ready():
        connect_new_client()

    for client in clients:
        if client.is_ready():
            get_input_from(client)

    update_program_state_based_on_input()

    for client in clients:
        if client.is_ready():
            send_output_to(client)

clean_up()

网络I / O当前使用套接字并选择,但我想重写它以使用asyncio库。我想我理解如何创建一个简单的asyncio程序,想法似乎是当你想做一些I / O时,你yield from一个函数来做它,所以当主循环得到一个新的客户端时,它会yield from accept_client(),当该客户端收到信息时,它会yield from read_information(),依此类推。但是,我无法弄清楚如何将其与程序的其他部分结合起来。

2 个答案:

答案 0 :(得分:3)

asyncio模块有两个级别的API:低级 transports & protocols API高级 streams API。它们就像不同的框架。根据您使用的API级别,您的程序结构可能会有很大差异。

为了防止你发疯,通常你不想混用这两个级别的API。

两个级别的不同之处在于以不同方式接收数据。低级API提供事件驱动的接口,您的程序通过实现回调来响应传入的事件 - 框架调用您的代码。高级API具有更好的外观,因为它提供了读者和编写者,您的代码调用框架

asyncio文档中的示例应该很容易理解。

答案 1 :(得分:2)

您的代码段大致描述了asyncio如何运作。

请查看asyncio example了解如何使用 asyncio:

import asyncio

@asyncio.coroutine
def echo_server():
    yield from asyncio.start_server(handle_connection, 'localhost', 8000)

@asyncio.coroutine
def handle_connection(reader, writer):
    while True:
        data = yield from reader.read(8192)
        if not data:
            break
        writer.write(data)

loop = asyncio.get_event_loop()
loop.run_until_complete(echo_server())
try:
    loop.run_forever()
finally:
    loop.close()