請求頭型別 post請求頭的常見型別
IO模型簡介
IO模型研究的主要是網路IO(linux系統)
基本關鍵字
同步(synchronous) 大部分情況下會採用縮寫的形式 sync
非同步(asynchronous) async
阻塞(blocking)
非阻塞(non-blocking)
五種IO
blocking IO 阻塞IO
nonblocking IO 非阻塞IO
IO multiplexing IO多路複用
signal driven IO 訊號驅動IO
asynchronous IO 非同步IO
由signal driven IO(訊號驅動IO)在實際中並不常用,所以主要介紹其餘四種IO Model。
再說一下IO發生時涉及的物件和步驟。對於一個network IO (這裡我們以read舉例),它會涉及到兩個系統物件,一個是呼叫這個IO的process (or thread),另一個就是系統核心(kernel)。當一個read操作發生時,該操作會經歷兩個階段:
1、等待資料準備 (Waiting for the data to be ready)
2、將資料從核心拷貝到程序中(Copying the data from the kernel to the process)
常見的網路阻塞狀態:
accept recv recvfrom
阻塞IO模型
讀操作流程大概是這樣:
在服務端開設多程序或者多執行緒 程序池執行緒池 其實還是沒有解決IO問題,該等的地方還是得等 沒有規避,只不過多個人等待的彼此互不干擾
非阻塞IO模型
服務端
import socket import time server = socket.socket() server.bind(('127.0.0.1', 8081)) server.listen(5) server.setblocking(False) # 將所有的網路阻塞變為非阻塞 r_list = [] del_list= [] while True: try: conn, addr = server.accept() r_list.append(conn) except BlockingIOError: # time.sleep(0.1) # print('列表的長度:',len(r_list)) # print('做其他事') for conn in r_list: try: data = conn.recv(1024) # 沒有訊息 報錯 if len(data) == 0: # 客戶端斷開連結 conn.close() # 關閉conn # 將無用的conn從r_list刪除 del_list.append(conn) continue conn.send(data.upper()) except BlockingIOError: continue except ConnectionResetError: conn.close() del_list.append(conn) # 揮手無用的連結 for conn in del_list: r_list.remove(conn) del_list.clear()
客戶端
import socket client = socket.socket() client.connect(('127.0.0.1',8081)) while True: client.send(b'hello world') data = client.recv(1024) print(data)
IO多路複用
服務端
import socket import select server = socket.socket() server.bind(('127.0.0.1',8080)) server.listen(5) server.setblocking(False) read_list = [server] while True: r_list, w_list, x_list = select.select(read_list, [], []) """ 幫你監管 一旦有人來了 立刻給你返回對應的監管物件 """ # print(res) # ([<socket.socket fd=3, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=('127.0.0.1', 8080)>], [], []) # print(server) # print(r_list) for i in r_list: # """針對不同的物件做不同的處理""" if i is server: conn, addr = i.accept() # 也應該新增到監管的佇列中 read_list.append(conn) else: res = i.recv(1024) if len(res) == 0: i.close() # 將無效的監管物件 移除 read_list.remove(i) continue print(res) i.send(b'heiheiheiheihei')
客戶端
import socket client = socket.socket() client.connect(('127.0.0.1',8080)) while True: client.send(b'hello world') data = client.recv(1024) print(data)
非同步IO
非同步IO模型是所有模型中效率最高的 也是使用最廣泛的
相關的模組和框架
模組:asyncio模組
非同步框架:sanic tronado twisted
import threading import asyncio @asyncio.coroutine def hello(): print('hello world %s'%threading.current_thread()) yield from asyncio.sleep(1) # 換成真正的IO操作 print('hello world %s' % threading.current_thread()) loop = asyncio.get_event_loop() tasks = [hello(),hello()] loop.run_until_complete(asyncio.wait(tasks)) loop.close()
IO模型比較分析