国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

python中使用asyncio實(shí)現(xiàn)異步IO實(shí)例分析

瀏覽:42日期:2022-06-27 09:47:21
1、說(shuō)明

Python實(shí)現(xiàn)異步IO非常簡(jiǎn)單,asyncio是Python 3.4版本引入的標(biāo)準(zhǔn)庫(kù),直接內(nèi)置了對(duì)異步IO的支持。

asyncio的編程模型就是一個(gè)消息循環(huán)。我們從asyncio模塊中直接獲取一個(gè)EventLoop的引用,然后把需要執(zhí)行的協(xié)程扔到EventLoop中執(zhí)行,就實(shí)現(xiàn)了異步IO。

2、實(shí)例

import asyncio@asyncio.coroutinedef wget(host): print(’wget %s...’ % host) connect = asyncio.open_connection(host, 80) reader, writer = yield from connect header = ’GET / HTTP/1.0rnHost: %srnrn’ % host writer.write(header.encode(’utf-8’)) yield from writer.drain() while True: line = yield from reader.readline() if line == b’rn’: 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()

知識(shí)點(diǎn)擴(kuò)展:

數(shù)據(jù)流(Streams)

數(shù)據(jù)流(Streams)是用于處理網(wǎng)絡(luò)連接的高階異步/等待就緒(async/await-ready)原語(yǔ),可以在不使用回調(diào)和底層傳輸協(xié)議的情況下發(fā)送和接收數(shù)據(jù)。

以下是一個(gè)用asyncio實(shí)現(xiàn)的TCP回顯客戶(hù)端:

import asyncioasync 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!’))

到此這篇關(guān)于python中使用asyncio實(shí)現(xiàn)異步IO實(shí)例分析的文章就介紹到這了,更多相關(guān)python中使用asyncio實(shí)現(xiàn)異步IO內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!

標(biāo)簽: Python 編程
相關(guān)文章:
主站蜘蛛池模板: 辽中县| 红安县| 水富县| 饶阳县| 万盛区| 同心县| 精河县| 泰州市| 沾益县| 来安县| 红河县| 弥渡县| 星座| 奉化市| 景谷| 海宁市| 奈曼旗| 巴林右旗| 嵩明县| 永和县| 乌拉特后旗| 嘉定区| 天镇县| 武隆县| 托克逊县| 长沙县| 汉阴县| 扶风县| 柏乡县| 长沙县| 繁峙县| 巍山| 蒲城县| 洪湖市| 修文县| 祁连县| 忻城县| 莱州市| 仁寿县| 武宣县| 巴青县|