Program structure using asyncio

Currently, I have a structure like:

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

Network I / O currently uses sockets and selects, but I want to rewrite it to use the asyncio library. I think that I understand how to make a simple asintio program, the idea is that when you want to do some I / O, you yield fromperform a function, so when the main loop receives a new client, it does yield from accept_client(), and when that client receives information he does yield from read_information()and so on. However, I cannot figure out how to combine this with other parts of the program.

+4
source share
2

, .

, asyncio, 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()
+2

asyncio API: API API. . API, , .

, API.

, -. API , , , - . API , , .

asyncio docs , .

+3

Source: https://habr.com/ru/post/1569054/


All Articles