python에서 asyncio를 사용하여 비동기 IO 실례 분석을 실현

1. 설명


Python은 비동기 IO를 실현하는 것이 매우 간단하다. asyncio는 Python 3.4 버전에 도입된 표준 라이브러리로 비동기 IO에 대한 지원을 직접 내장했다.
asyncio의 프로그래밍 모델은 메시지 순환이다.우리는 asyncio 모듈에서 EventLoop의 인용을 직접 얻고 실행해야 할 협정을 EventLoop에 던져 실행하면 비동기 IO를 실현할 수 있다.

2. 인스턴스


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
Host: %s\r
\r
' % host writer.write(header.encode('utf-8')) yield from writer.drain() while True: line = yield from reader.readline() if line == b'\r
': 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()
지식 포인트 확장:
데이터 스트림(Streams)
데이터 흐름(Streams)은 네트워크 연결을 처리하는 데 사용되는 고급 비동기/대기 준비(async/await-ready) 원어로 리셋과 베이스 전송 프로토콜을 사용하지 않고 데이터를 전송하고 수신할 수 있습니다.
다음은 asyncio로 구현된 TCP 리셋 클라이언트입니다.

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!'))
이는python에서 asyncio를 사용하여 비동기 IO를 실현하는 실례 분석에 관한 글을 소개합니다. 더 많은 관련python에서 asyncio를 사용하여 비동기 IO를 실현하는 내용은 이전의 글을 검색하거나 아래의 관련 글을 계속 훑어보십시오. 앞으로 많은 응원 부탁드립니다!

좋은 웹페이지 즐겨찾기