Python - select() 没有捕捉到损坏的套接字

标签 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()

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

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

最佳答案

当远程端完全关闭套接字时,它将对您变得“可读”。当您调用 recv() 时,您将返回 个字节。您的代码不会在 if data:else: 子句中执行任何操作。这是您应该放置对关闭的套接字作出 react 的代码的地方。

关于Python - select() 没有捕捉到损坏的套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13257047/

相关文章:

Python如何区分python套接字模块中的数据(当服务器接收时。)

MySQL : Make HAVING select also "null"

mysql - 在 mysql 语句中使用 'as' 时出现未知列错误

python - cv2.line 和 cv2.circle 返回 None

python - 如何将字符串的每个字符转换为 ASCII 并填充到给定长度

sockets - 代理服务器如何与 tcp/http 连接一起工作?

sql-server - 两个选择的公共(public)组,sql server

python - pandas TimeGrouper 自定义频率时间范围

python - 加入守护线程

java - 通过 Java Socket 发送对象真的很慢