select必須傳入三個參數分別是三個列表read_list, write_list, erro_list返回值是一個元祖對應傳入的參數
linux
#select幫助感知某個IO操做是否有變更 #read開始被read #write開始被write #erro開始有erro #一但感知到就會返回響應的參數 import socket from select import select sk = socket.socket() address = ('127.0.0.1', 8080) sk.bind(address) sk.setblocking(False) sk.listen() #監聽 read_ls = [sk] #將sk對象加入一個列表 while 1: r_ls, w_ls, x_ls = select(read_ls, [], []) for i in r_ls: if i is sk: conn, addr = i.accept() read_ls.append(conn) else: ret = i.recv(1024) #接收消息 if ret == b'': read_ls.remove(i) i.close() continue print(ret) i.send(b'byebye!') #發送消息
客戶端 -起多線程的客戶端windows
import socket from threading import Thread def func(): sk = socket.socket() address = ('127.0.0.1', 8080) sk.connect(address) sk.send(b'hello') ret = sk.recv(1024) print(ret) sk.close() t_ls = [] for i in range(10): t = Thread(target=func) t.start()
select
機制基本上同樣poll
監聽的對象比select
監聽上限多