rlms
rlms

Reputation: 11060

Program structure using asyncio

I currently have a program structured like this:

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()

The network I/O currently uses sockets and select, but I want to rewrite it to use the asyncio library. I think I understand how to make a simple asyncio program, the idea seems to be that when you want to do some I/O, you yield from a function that does it, so when the main loop gets a new client, it does yield from accept_client(), and when that client receives information it does yield from read_information(), and so on. However, I can't work out how to combine this with other parts of the program.

Upvotes: 4

Views: 745

Answers (2)

l04m33
l04m33

Reputation: 606

The asyncio module has two levels of APIs: The low-level transports & protocols API and the high-level streams API. They are like different frameworks. Depending on the API level you are using, your program structure may differ dramatically.

To prevent yourself from going crazy, normally you don't want to mix these two levels of APIs.

The two levels differ in that you receive data in different ways. The low-level API provides an event-driven interface, your program responds to incoming events by implementing callbacks - The framwork calls your code. The high-level API have a nicer look, in that it provides readers & writers, and your code calls the framework.

The examples in asyncio docs should be easy enough to follow.

Upvotes: 3

Andrew Svetlov
Andrew Svetlov

Reputation: 17386

Your snippet roughly describes how asyncio works itself.

Please take a look on asyncio example for how to use 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()

Upvotes: 2

Related Questions