目的:同一个线程同时处理多个IO请求。

  本文以python的select模块来实现socket编程中一个server同时处理多个client请求的问题。

  web框架tornado就是以此实现多客户端连接问题的。以下为select源码说明:

def select(rlist, wlist, xlist, timeout=None): # real signature unknown; restored from __doc__
    """
    select(rlist, wlist, xlist[, timeout]) -> (rlist, wlist, xlist)
    
    Wait until one or more file descriptors are ready for some kind of I/O.
    The first three arguments are sequences of file descriptors to be waited for:
    rlist -- wait until ready for reading
    wlist -- wait until ready for writing
    xlist -- wait for an ``exceptional condition''
    If only one kind of condition is required, pass [] for the other lists.
    A file descriptor is either a socket or file object, or a small integer
    gotten from a fileno() method call on one of those.
    
    The optional 4th argument specifies a timeout in seconds; it may be
    a floating point number to specify fractions of seconds.  If it is absent
    or None, the call will never time out.
    
    The return value is a tuple of three lists corresponding to the first three
    arguments; each contains the subset of the corresponding file descriptors
    that are ready.
    
    *** IMPORTANT NOTICE ***
    On Windows and OpenVMS, only sockets are supported; on Unix, all file
    descriptors can be used.
    """
    pass

# classes

 

实例1

server端

#!/usr/bin/env python
#-*- coding:utf-8 -*-
import socket
import select
ss = socket.socket()
ss.bind(("localhost",8000))
ss.listen(5)
ss.setblocking(False)

inputs = [ss]
while True:
    rList,wList,e = select.select(inputs,[],[],2)
    print "inputs:", inputs
    print "resaults:", rList
    for r in rList:
        if r == ss:
            con,addr = r.accept()
            inputs.append(con)
        else:
        
        
            try:
                data = r.recv(1024)
            except socket.error,e:
                inputs.remove(r)
            else:
                r.send(data)
server

相关文章: