import selectors import socket sel = selectors.DefaultSelector() def accept(sock, mask): conn, addr = sock.accept() # Should be ready 建立连接 print(‘accepted‘, conn, ‘from‘, addr) conn.setblocking(False) sel.register(conn, selectors.EVENT_READ, read)#注册到时间循环列表(不立刻收,客户端可能还没有发。)如果再有活动就调用read函数 def read(conn, mask): data = conn.recv(1000) # Should be ready if data: print(‘echoing‘, repr(data), ‘to‘, conn) conn.send(data) # Hope it won‘t block else: print(‘closing‘, conn) sel.unregister(conn) conn.close() sock = socket.socket() sock.bind((‘localhost‘, 1234)) sock.listen(100) sock.setblocking(False) sel.register(sock, selectors.EVENT_READ, accept)#先注册server对象。调用accept while True: events = sel.select() #默认阻塞,有活动链接就返回活动列表 for key, mask in events: callback = key.data callback(key.fileobj, mask)
使用示例2
#服务端 from socket import * import selectors sel=selectors.DefaultSelector() def accept(server_fileobj,mask): conn,addr=server_fileobj.accept() sel.register(conn,selectors.EVENT_READ,read) def read(conn,mask): try: data=conn.recv(1024) if not data: print(‘closing‘,conn) sel.unregister(conn) conn.close() return conn.send(data.upper()+b‘_SB‘) except Exception: print(‘closing‘, conn) sel.unregister(conn) conn.close() server_fileobj=socket(AF_INET,SOCK_STREAM) server_fileobj.setsockopt(SOL_SOCKET,SO_REUSEADDR,1) server_fileobj.bind((‘127.0.0.1‘,8088)) server_fileobj.listen(5) server_fileobj.setblocking(False) #设置socket的接口为非阻塞 sel.register(server_fileobj,selectors.EVENT_READ,accept) #相当于网select的读列表里append了一个文件句柄server_fileobj,并且绑定了一个回调函数accept while True: events=sel.select() #检测所有的fileobj,是否有完成wait data的 for sel_obj,mask in events: callback=sel_obj.data #callback=accpet callback(sel_obj.fileobj,mask) #accpet(server_fileobj,1) #客户端 from socket import * c=socket(AF_INET,SOCK_STREAM) c.connect((‘127.0.0.1‘,8088)) while True: msg=input(‘>>: ‘) if not msg:continue c.send(msg.encode(‘utf-8‘)) data=c.recv(1024) print(data.decode(‘utf-8‘))
原文:https://www.cnblogs.com/ahliucong/p/9404141.html