一、select模块
- Python select socket server代码示例
# Author:Li Dongfei
import select, socket, sys, queue
server = socket.socket()
server.bind(('localhost', 9000))
server.listen(1000)
server.setblocking(False) #设置为非阻塞
msg_dic = {}
inputs = [server,]
outputs = []
while True:
readable, writeable, exceptional = select.select(inputs, outputs, inputs)
print(readable,writeable,exceptional)
for r in readable:
if r is server:
conn, addr = server.accept()
print("new connect", addr)
inputs.append(conn)
msg_dic[conn] = queue.Queue()
else:
data = r.recv(1024)
print("recv data",data)
msg_dic[r].put(data)
outputs.append(r)
for w in writeable:
data_to_clinet =msg_dic[w].get()
w.send(data_to_clinet)
outputs.remove(w)
for e in exceptional:
if e in outputs:
outputs.remove(e)
inputs.remove(e)
del msg_dic[e]
二、selector模块
# Author:Li Dongfei
import selectors, socket
sel = selectors.DefaultSelector()
def accept(sock, mask):
conn, addr = sock.accept()
print('accepted', conn, 'from', addr)
conn.setblocking(False)
sel.register(conn, selectors.EVENT_READ, read)
def read(conn, mask):
data = conn.recv(1024)
if data:
print('echoing', repr(data), 'to', conn)
conn.send(data)
else:
print('closing', conn)
sel.unregister(conn)
conn.close()
sock = socket.socket()
sock.bind(('localhost', 9000))
sock.listen(1000)
sock.setblocking(False)
sel.register(sock, selectors.EVENT_READ, accept)
while True:
events = sel.select()
for key, mask in events:
callback = key.data
callback(key.fileobj, mask)