Example analysis of asynchronous IO using asyncio in python

  • 2021-09-11 20:41:56
  • OfStack

1. Description

Python is very simple to implement asynchronous IO, and asyncio is a standard library introduced in Python version 3.4, which directly builds in support for asynchronous IO.

The programming model of asyncio is a message loop. We directly obtain a reference of EventLoop from asyncio module, and then throw the coprocess to EventLoop for execution, thus realizing asynchronous IO.

2. Examples


import asyncio
@asyncio.coroutine
def wget(host):
  print('wget %s...' % host)
  connect = asyncio.open_connection(host, 80)
  reader, writer = yield from connect
  header = 'GET / HTTP/1.0\r\nHost: %s\r\n\r\n' % host
  writer.write(header.encode('utf-8'))
  yield from writer.drain()
  while True:
    line = yield from reader.readline()
    if line == b'\r\n':
      break
    print('%s header > %s' % (host, line.decode('utf-8').rstrip()))
  # Ignore the body, close the socket
  writer.close()
loop = asyncio.get_event_loop()
tasks = [wget(host) for host in ['www.sina.com.cn', 'www.sohu.com', 'www.163.com']]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()

Extension of knowledge points:

Data Stream (Streams)

Data Stream (Streams) is a high-order asynchronous/wait-ready (async/await-ready) primitive for handling network connections that can send and receive data without using callbacks and underlying transport protocols.

The following is an TCP Echo client implemented with asyncio:


import asyncio

async def tcp_echo_client(message):
  reader, writer = await asyncio.open_connection(
    '127.0.0.1', 8888)

  print(f'Send: {message!r}')
  writer.write(message.encode())

  data = await reader.read(100)
  print(f'Received: {data.decode()!r}')

  print('Close the connection')
  writer.close()
  await writer.wait_closed()

asyncio.run(tcp_echo_client('Hello World!'))

Related articles: