python selectors
客户端
import socket sock=socket.socket() sock.connect(("127.0.0.1",8080)) while 1: msg=input("input>>>:") sock.send(msg.encode("utf8")) data=sock.recv(1024) print(data.decode("utf8")) sock.close()
服务端
import selectors import socket sock=socket.socket() sock.bind(("127.0.0.1",8080)) sock.listen(5) sock.setblocking(False) #根据具体平台选择最佳IO多路机制,比如在Linux,选择epoll sel=selectors.DefaultSelector() def read(conn,mask): try: data =conn.recv(1024) print(data.decode("utf8")) msg=input(">>>:") conn.send(msg.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 1: print("waiting....") # 监听[(key1,mask1),(key2,mask2)] events=sel.select() for key,mask in events: # print(key.fileobj) #conn # print(key.data) #read func=key.data obj=key.fileobj # 1 accept(sock,mask) # 2 read(conn,mask) func(obj,mask)
基于select模块实现io多路复用
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 1: 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)