select 实现server I/O多路复用通信
生活随笔
收集整理的這篇文章主要介紹了
select 实现server I/O多路复用通信
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
- 非阻塞模式下客戶端發生異常或服務器未處理完數據,就會立刻返回錯誤,不用等待
服務器端
- 建立連接
- 設置為非阻塞模式
- 使用select進行監測
- 判斷最開始inputs里是否是server,是的話表示建立了連接
- 不是代表客戶端開始發送數據,服務器接收數據并放入之前初始化的隊列中
- 向客戶端發送數據,發送完畢從隊列中移除連接
- 異常處理
服務器端完整代碼
#select模擬socketserver import select,queue,socket server=socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(('localhost',2223)) server.listen(5) server.setblocking(False) inputs=[server,]#一開始要先監測server,知道是否建立連接 outputs=[] msg_dic={} while True:readable, writable, excetional = select.select(inputs, outputs, inputs) # select 進行監聽for r in readable:if r is server:#表示建立連接conn,addr=server.accept()conn.setblocking(False)#非阻塞inputs.append(conn)#select監測連接過來的實例'''新建立的連接還沒發數據過來,現在就接收數據的話是空的,會報錯,因此要讓select監測每一個連接過來的連接,這樣才知道客戶端發送數據過來'''msg_dic[conn]=queue.Queue()#初始化一個隊列,用于存放每一個連接的數據print('建立連接',addr)else:try:data=r.recv(1024)#不可以直接判斷數據是否為空,因為客戶端斷開時服務器已經接收不到數據了#有數據發送過來print(data.decode())msg_dic[r].put(data)if r not in outputs:outputs.append(r) # 放入返回的連接隊列里,下一次循環select檢測的時候發給客戶端except ConnectionResetError as e:#處理沒有數據的情況,即服務器斷開print(addr,' is close...')if r in outputs:#移除連接 outputs.remove(r)inputs.remove(r)r.close()del msg_dic[r]breakfor w in writable:try:next_msg = msg_dic[w].get_nowait()#從隊列中取元素,不等待except queue.Empty:# print('output queue for', w.getpeername(), 'is empty') outputs.remove(w)else:# print('sending "%s" to %s' % (next_msg, w.getpeername())) w.send(next_msg)# outputs.remove(w)#從outputs中移除舊的連接for e in excetional:#發生異常就將連接移除 inputs.remove(e)if e in outputs:outputs.remove(e)e.close()del msg_dic[e]#從隊列中移除連接 View Code注:判斷客戶端是否斷開時,要用捕獲異常來處理,不能直接判斷服務器接收的數據是否為空,因為此時客戶端已經斷開了,服務器無法接收數據了,會報ConnectionResetError
客戶端完整代碼
import socket client=socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect(('localhost',2223)) while True:cmd=input(">>>")if cmd=='':continueclient.send(cmd.encode())data=client.recv(1024)print(data.decode()) View Code?
轉載于:https://www.cnblogs.com/Aprilnn/p/9318306.html
總結
以上是生活随笔為你收集整理的select 实现server I/O多路复用通信的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Vue学习笔记5
- 下一篇: 实验 3:备份和还原配置文件