多路复用
服务端 from socket import * import time import select server = socket(AF_INET,SOCK_STREAM) server.bind(('127.0.0.1',8081)) server.listen(3) server.setblocking(False) #accept变为非阻塞状态, print('server startting...') reads_l = [server,] #每次来一个客户端,添加到列表 while True: r_l,_,_ = select.select(reads_l,[],[]) for obj in r_l: #接收到的对象 if obj == server: #server.accept conn,addr = server.accept conn,addr = obj.accept() #每个对象都有conn,addr reads_l.append(conn) else: # conn.recv 接收到的数据 data = obj.recv(1024) #obj = conn obj.send(data.upper()) 客户端 from socket import * client = socket(AF_INET,SOCK_STREAM) client.connect(('127.0.0.1',8081)) while True: msg = input('p;ease:').strip() if not msg:continue client.send(msg.encode('utf-8')) data = client.recv(1024) print(data.decode('utf-8'))
selector模块使用:
#服务端 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)
# 将conn,注册到sel中 def read(conn,mask): try: data=conn.recv(1024) if not data:
# 如果没有数据,删除掉conn print('closing',conn) sel.unregister(conn) conn.close() return conn.send(data.upper()+b'_SB') except Exception:
# 如果出现异常,删除掉conn 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'))
本文来自博客园,作者:一石数字欠我15w!!!,转载请注明原文链接:https://www.cnblogs.com/52-qq/p/7464692.html