首页 > 代码库 > selectors实现高并发
selectors实现高并发
1. 下面的例子,客户端给服务端发送消息,服务端把消息返回
server
#!/usr/bin/env pythonimport selectorsimport socketimport timeimport threadingsel = selectors.DefaultSelector()def echo(conn,cmd,filename): time.sleep(3) conn.send((cmd + ‘ ‘ + filename).encode())def accept_client(sock,mask): conn,addr = sock.accept() print(‘conn:{},addr:{},mask:{}‘.format(conn,addr,mask))# conn.setblocking(False) sel.register(conn, selectors.EVENT_READ, read_client)def read_client(conn,mask): data = conn.recv(1024).decode().strip() if data: if len(data.split(‘ ‘)) == 2: cmd = data.split(‘ ‘)[0] filename = data.split(‘ ‘)[1] t = threading.Thread(target=echo,args=(conn,cmd,filename)) #这里使用了线程,不然程序会变成串行的,执行一个客户端任务,sleep(3)然后再执行下一个客户端任务... t.start()# time.sleep(1)# conn.send((cmd + ‘ ‘ + filename).encode()) else: conn.send((‘usage: put filename ;get filename‘).encode()) else: print(‘{} closed‘.format(conn)) sel.unregister(conn) conn.close()server = socket.socket()server.bind((‘localhost‘,1235))server.listen(12340)# server.setblocking(False)sel.register(server, selectors.EVENT_READ,accept_client)while True: events = sel.select() for key,mask in events: callable = key.data callable(key.fileobj,mask)
client
#!/usr/bin/env pythonimport socketimport threadingimport timeip_port = (‘localhost‘,1235)socks = [socket.socket() for i in range(1000)] m = b‘get abc‘time_list = []def run(s): s.connect(ip_port) s.send(m) data = s.recv(1024) print(s,data) start_time = time.time() for s in socks: t = threading.Thread(target=run,args=(s,)) t.start() time_list.append(t)for i in time_list: i.join()print(‘time:{}‘.format(start_time - time.time()))
2. 实现并发put和get文件
selectors实现高并发
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。