select模块
selectors模块
基于select模块实现的io多路复用。
server.py
:
python
import selectors # 基于select模块实现的IO多路复用,建议大家使用
import socket
sock=socket.socket()
sock.bind(("127.0.0.1",8800))
sock.listen(5)
sock.setblocking(False)
sel=selectors.DefaultSelector() #根据具体平台选择最佳IO多路机制,比如在linux,选择epoll
def read(conn,mask):
try:
data=conn.recv(1024)
print(data.decode("UTF8"))
data2=input(">>>")
conn.send(data2.encode("utf8"))
except Exception:
sel.unregister(conn)
def accept(sock,mask):
conn, addr = sock.accept()
print("conn",conn)
sel.register(conn,selectors.EVENT_READ,read)
sel.register(sock,selectors.EVENT_READ,accept) # 注册事件
while True:
print("wating...")
events=sel.select() # 监听 [(key1,mask1),(key2,mask2)]
for key,mask in events:
# print(key.fileobj) # conn
# print(key.data) # read
func=key.data
obj=key.fileobj
func(obj,mask) # 1 accept(sock,mask) # 2 read(conn,mask)
client.py
:
python
import socket
client = socket.socket()
# 阻塞
client.connect(('127.0.0.1', 8800))
while True:
content = input(">>>")
if content.upper() == 'Q':
break
client.sendall(content.encode('utf-8'))
client.close()