3

我正在用 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()

客户端正常关闭socket时,不被select捕获,客户端中断socket时,不被`exception捕获。

如何使该服务器对关闭/损坏的套接字具有鲁棒性?

4

1 回答 1

3

当远程端干净地关闭套接字时,它将变得对您“可读”。当您调用 时recv(),您将获得字节。您的代码else:if data:. 这是您应该放置对关闭的套接字做出反应的代码的地方。

于 2012-11-06T18:30:33.550 回答