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를 실현하는 내용은 이전의 글을 검색하거나 아래의 관련 글을 계속 훑어보십시오. 앞으로 많은 응원 부탁드립니다!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
로마 숫자를 정수로 또는 그 반대로 변환그 중 하나는 로마 숫자를 정수로 변환하는 함수를 만드는 것이었고 두 번째는 그 반대를 수행하는 함수를 만드는 것이었습니다. 문자만 포함합니다'I', 'V', 'X', 'L', 'C', 'D', 'M' ; 문자열이 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.