Python - select()不会捕获断开的套接字

时间:2012-11-06 18:26:40

标签: python sockets select

我正在用Python实现一个服务器。我一直在关注Doug Hellmann's blog上的教程:

我遇到问题,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()

当客户端正常关闭套接字时,它不会被select捕获,当客户端断开套接字时,它不会被“异常”捕获。

如何使此服务器对已关闭/已损坏的套接字具有健壮性?

1 个答案:

答案 0 :(得分:3)

当远程端完全关闭套接字时,它将变为“可读”。当您致电recv()时,您将获得字节。您的代码在else:的{​​{1}}子句中没有执行任何操作。这是你应该把代码放在一个封闭的套接字上的地方。