python中的select模組專注於i/o多路復用,提供了select poll epoll三個方法(其中後兩個在linux中可用,windows僅支援select),另外也提供了kqueue方法(freebsd系統)
r_list,w_list,e_list = select.select(rlist, wlist, xlist, [timeout])
三個引數
wlist
xlist
timeout
示例:服務端
客戶端import socket
import time
import select
s = socket.socket()
s.bind(("127.0.0.1",1688))
# 設定為非阻塞 模型
s.setblocking(true) #在多路復用中 阻塞與非阻塞沒有區別 因為select會阻塞直到有資料到達為止
s.listen(5)
# 待檢測是否可讀的列表
r_list = [s]
# 待檢測是否可寫的列表
w_list =
# 待傳送的資料
msgs = {}
print("開始檢測了")
while true:
read_ables, write_ables, _= select.select(r_list,w_list,)
print("檢測出結果了!")
# print(read_ables,"可以收資料了")
# print(write_ables,"可以發資料了")
# 處理可讀 也就是接收資料的
for obj in read_ables: # 拿出所有可以讀資料的socket
#有可能是伺服器 有可能是客戶端
if s == obj: # 伺服器
print("來了乙個客戶端 要連線")
client,addr = s.accept()
else:# 如果是客戶端則執行recv 接收資料
print("客戶端發來乙個資料")
data = obj.recv(1024)
print("有個客戶端說:",data)
# 將要傳送資料的socket加入到列表中讓select檢測
# 將要傳送的資料已經socket物件丟到容器中
if obj in msgs: # 由於容器是乙個列表 所以需要先判斷是否已經存在了列表
else:
msgs[obj] = [data]
# 處理可寫的 也就是send傳送資料
for obj in write_ables:
msg_list = msgs.get(obj)
if msg_list:
# 遍歷傳送所有資料
for m in msg_list:
obj.send(m.upper())
# 資料從容器中刪除
msgs.pop(obj)
# 將這個socket從w_list中刪除
w_list.remove(obj)
import socket
c = socket.socket()
c.connect(("127.0.0.1",1688))
while true:
msg = input("").strip()
if not msg:continue
c.send(msg.encode("utf-8"))
print(c.recv(1024).decode('utf-8'))
後續幾種方法以後總結補充
IO多路復用 select
select系統呼叫的目的是 在一段指定時間內,監聽使用者感興趣的檔案描述符上的可讀 可寫和異常事件。poll和select應該被歸類為這樣的系統 呼叫,它們可以阻塞地同時探測一組支援非阻塞的io裝置,直至某乙個裝置觸發了事件或者超過了指定的等待時間 也就是說它們的職責不是做io,而是幫助 呼叫者尋...
IO多路復用 select
出自朱有鵬老師的課堂 include include include include include include include include include int main void 當前有兩個fd,乙個是fd乙個是0 處理 myset fd zero myset 全部清零 fd set ...
I O多路復用 select
int select int n,fd set readfds,fd set writefds,fd set exceptfds,struct timeval timeout 有三種型別的描述符型別 readset writeset exceptset,分別對應讀 寫 異常條件的描述符集合。fd s...