一下代码,是摘自大王的博客,(http://www.cnblogs.com/alex3714/)我自己有加了些注释。

1  
  2 
  3 #_*_coding:utf-8_*_
  4 
  5 __author__ = 'Alex Li'
  6  
  7 import select
  8 import socket
  9 import sys
 10 import queue
 11  
 12 # Create a TCP/IP socket
 13 server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 14 #创建一个socket,作用和文件描述符差不多(基于linux一切皆文件的哲学思想),recv相当于read(),send相当于write()。默认socket.socket默认就是加socket.AF_INET, socket.SOCK_STREAM这两个参数。
 15 server.setblocking(False)
 16 #sk.setblocking(bool) 是否阻塞(默认True),如果设置False,那么accept和recv时一旦无数据,则报错。accept和recv默认是阻塞的。
 17  
 18 # Bind the socket to the port
 19 server_address = ('localhost', 10000)
 20 print(sys.stderr, 'starting up on %s port %s' % server_address)
 21 server.bind(server_address)
 22  
 23 # Listen for incoming connections
 24 server.listen(5)
 25 #理论上监听队列的长度(backlog)就是取listen和maxconn(系统层次的限定值)的最小值()
 #如果客户端没有被处理的请求数超过了这个值,或者请求了一个没有侦听的端口就会报(socket.error: [Errno 10061] )
# 5,表示内核已经接到了连接请求,但服务器还没有调用accept进行处理的连接个数最大为5
      这个值不能无限大,因为要在内核中维护连接队列
 26  
 27 # Sockets from which we expect to read
 28 inputs = [ server ]
 29  
 30 # Sockets to which we expect to write
 31 outputs = [ ]
 32  
 33 message_queues = {}
 34 while inputs:
 35  
 36     # Wait for at least one of the sockets to be ready for processing
 37     print( '\nwaiting for the next event')
 38     readable, writable, exceptional = select.select(inputs, outputs, inputs)
 39     # Handle inputs
 40     for s in readable:
 41  
 42         if s is server:
 43             # A "readable" server socket is ready to accept a connection
 44             connection, client_address = s.accept()
 45             print('new connection from', client_address)
 46             connection.setblocking(False)
 47 #将这个socket设置成非阻塞的。这个socket的recv和accept就不会阻塞了。
 48             inputs.append(connection)
 49  
 50             # Give the connection a queue for data we want to send
 51             message_queues[connection] = queue.Queue()
 52 #创建一个字典的key和value,value就是一个队列的实例。
 53         else:
 54             data = s.recv(1024)
 55             if data:
 56                 # A readable client socket has data
 57                 print(sys.stderr, 'received "%s" from %s' % (data, s.getpeername()) )
 58                 message_queues[s].put(data)
 59                 # Add output channel for response
 60                 if s not in outputs:
 61                     outputs.append(s)
 62             else:
 63                 # Interpret empty result as closed connection
 64                 print('closing', client_address, 'after reading no data')
 65                 # Stop listening for input on the connection
 66                 if s in outputs:
 67                     outputs.remove(s)  #既然客户端都断开了,我就不用再给它返回数据了,所以这时候如果这个客户端的连接对象还在outputs列表中,就把它删掉
 68                 inputs.remove(s)    #inputs中也删除掉
 69                 s.close()           #把这个连接关闭掉
 70  
 71                 # Remove message queue
 72                 del message_queues[s]
 73     # Handle outputs
 74     for s in writable:
 75         try:
 76             next_msg = message_queues[s].get_nowait()
 77 """get_nowait:Remove and return an item from the queue without blocking.
 78 
 79 Only get an item if one is immediately available. Otherwise
 80 raise the Empty exception.
 81 """
 82         except queue.Empty:
 83             # No messages waiting so stop checking for writability.
 84             print('output queue for', s.getpeername(), 'is empty')
 85 #getpeername()返回连接套接字的远程地址。返回值通常是元组(ipaddr,port)。
 86             outputs.remove(s)
 87         else:
 88             print( 'sending "%s" to %s' % (next_msg, s.getpeername()))
 89             s.send(next_msg)
 90     # Handle "exceptional conditions"
 91     for s in exceptional:
 92         print('handling exceptional condition for', s.getpeername() )
 93         # Stop listening for input on the connection
 94         inputs.remove(s)
 95         if s in outputs:
 96             outputs.remove(s)
 97         s.close()
 98  
 99         # Remove message queue
100         del message_queues[s]
view code