select方法:
import socket, select s = socket.socket() host = socket.gethostname() port = 1234 s.bind((host, port)) s.listen(5) inputs = [s] while True: rs, ws, es = select.select(inputs, [], []) for r in rs: if r is s: c, addr = s.accept() print ‘Got connection from‘, addr inputs.append(c)
else:
try:
data = r.recv(1024)
disconnected = not data
except socket.error:
disconnected = True
if disconnected:
print r.getpeername(), ‘disconnected‘
inputs.remove(r)
else:
print data
poll方法: import socket, select s = socket.socket() host = socket.gethostname() port = 1234 s.bind((host, port)) fdmap = {s.fileno(): s} s.listen(5) p = select.poll() p.register(s) while True: events = p.poll() for fd, event in events: if fd in fdmap: c, addr = s.accept() print ‘Got connection from‘, addr p.register(c) fdmap[c.fileno()] = c elif event & select.POLLIN: data = fdmap[fd].recv(1024) if not data: # No data -- connection closed print fdmap[fd].getpeername(), ‘disconnected‘ p.unregister(fd) del fdmap[fd] else: print data
原文:http://www.cnblogs.com/zhuweiblog/p/5186631.html