2012-11-06 17 views
3

我正在Python中实现一个服务器。我一直在关注Doug Hellmann's blog上的教程:Python - select()不会捕获破损的套接字

我遇到了一个问题,select()没有捕获破损或关闭的管道。

# Create socket 
    serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
    # Non blocking socket 
    serversocket.setblocking(0) 
    # Bind socket 
    serversocket.bind((HOST, PORT)) 
    # Socket listening 
    serversocket.listen(5) 

    # Sockets from which we expect to read 
    inputs = [ serversocket ] 
    # Sockets to which we expect to write 
    outputs = [ ] 

    resign = re.compile("resign") 

    while inputs: 
     print "Waiting for connection..." 
     readable, writable, exceptional = select.select(inputs, outputs, inputs) 

     for s in exceptional: 
      print >>sys.stderr, 'handling exceptional condition for', s.getpeername() 
      # Stop listening for input on the connection 
      inputs.remove(s) 
      s.close() 


     for s in readable: 
      # SERVER LISTENS TO CONNEXION 
      if s is serversocket: 

       if some_stuff_is_true: 
        connection, client_address = s.accept(); 
        print 'New connection from ', client_address 
        connection.setblocking(0) 
        inputs.append(connection) 


      # CLIENT READABLE 
      else: 
       data = s.recv(MAXLINE) 
       #If socket has data to be read 
       if data: 
        print data # Test if data correclty received 
        if resign.findall(data): 
         inputs.remove(s) 
         s.close() 

当客户端正常关闭套接字,它不是由选择赶,当客户突破插座,它不是由`特殊捕获。

如何使此服务器对闭合/断开的插座稳健?

回答

3

当套接字被远端完全关闭时,它会变得“可读”。当您拨打recv()时,您会收到零回字节。您的代码在if data:else:条款中没有做任何事情。这是你应该把代码反应到一个封闭的套接字的地方。

+0

与那些没有发送数据的套接字有区别吗? –

+0

那些没有正确关闭的插座呢?不应该被'特殊'抓住? –

+0

尚未发送数据的套接字未显示为“可读”。没有正确关闭的套接字可能会显示为“异常”,或者可能显示为“可读”,并在调用'recv()'时导致Python异常。您需要为您的操作系统试验和/或阅读文档,以了解每种特定情况下的情况。 –