IO多路复用之select
Posted fly10086
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了IO多路复用之select相关的知识,希望对你有一定的参考价值。
1 import socket,select,queue 2 3 server = socket.socket() 4 server.bind((‘127.0.0.1‘,9000)) 5 server.listen(1000) 6 server.setblocking(0) 7 8 inputs = [server] 9 outputs = [] 10 que_dic = {} 11 12 13 14 while True: 15 readable, writable, E = select.select(inputs, outputs, inputs) 16 try: 17 for r in readable: 18 if r is server: 19 conn,addr = r.accept() 20 print(‘----{}----‘.format(addr)) 21 inputs.append(conn) 22 que_conn = queue.Queue() 23 que_dic[conn] = que_conn 24 else: 25 data = r.recv(1024) 26 print(‘收到>>>‘,data.decode(‘utf8‘)) 27 que_dic[r].put(data) 28 outputs.append(r) 29 for w in writable: 30 data = que_dic[w].get() 31 w.sendall(data) 32 outputs.remove(w) 33 except Exception: 34 for e in E: 35 del que_dic[e] 36 if e in outputs:outputs.remove(e) 37 print(inputs) 38 inputs.remove(e) 39 print(inputs)
client 端
1 import socket,select,queue 2 3 client = socket.socket() 4 client.connect((‘127.0.0.1‘,8000)) 5 while True: 6 msg = input(‘>>>:‘) 7 client.sendall(msg.encode(‘utf8‘)) 8 data = client.recv(1024) 9 print(‘收到返回信息:‘,data.decode(‘utf8‘))
以上是关于IO多路复用之select的主要内容,如果未能解决你的问题,请参考以下文章