1 # 使用select的简单服务器 2 import socket, select 3 4 s = socket.socket() 5 6 host = socket.gethosename() 7 prot = 1234 8 s.bind((host, port)) 9 s.listen(5) 10 inputs = [s] 11 while True: 12 rs, ws, es = select.select(inputs, [], []) 13 for r in rs: 14 if r is s: 15 c, addr = s.accept() 16 print('Got connection from ', addr) 17 inputs.append(c) 18 else: 19 try: 20 data = r.recv(1024) 21 disconnected = not data 22 except socket.error: 23 disconnected = True 24 25 if disconnected: 26 print(r.getpeername(), 'disconnected') 27 inputs.remove(r) 28 else: 29 print(data) 30