python -select()不会捕获破裂的插座



我正在Python中实现服务器。我一直在关注道格·赫尔曼(Doug Hellmann)博客上的教程:

我有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()

当客户端正常关闭套接字时,它不会被选择捕获,并且当客户端破坏套接字时,它不会被``extrac offection''捕获。

如何使该服务器稳健地关闭/折断插座?

当插座用遥控端干净地关闭时,它将成为您的"可读性"。调用recv()时,您将获得 bytes。您的代码在if data:else:子句中不执行任何操作。这是您应该放置对封闭插座的代码的地方。

最新更新