接收带有套接字的大型腌制对象时无限循环

infinite loop when receiving a large pickled object with sockets

我正在使用远程 linux 服务器,我想通过来自客户端的套接字使用 python 发送数组,所以我使用了以下代码:

message = pickle.dumps(faceBlob)
message_header = bytes(f"{len(message):<{HEADER_LENGTH}}", "utf-8")
client_socket.send(message_header + message)

为了在服务器中接收它,我使用了一个 while 循环来捕获所有消息,因为它大于 4096 :

def receive_blop(client_socket):
    # Receive our "header" containing message length, it's size is defined and constant
    message_header = client_socket.recv(HEADER_LENGTH)

    # If we received no data, client gracefully closed a connection, for example using socket.close() or socket.shutdown(socket.SHUT_RDWR)
    if not len(message_header):
        return False

    # Convert header to int value
    message_length = int(message_header.decode('utf-8').strip())
    fragments = []
    print(message_length)

    while True:
        # this loop is infinite

        print("I arrived her")
        chunk = client_socket.recv(4096)
        if not chunk:
            break
        fragments.append(chunk)

    data_arr = b"".join(fragments)


    # Return an object of message header and message data
    return {'header': message_header, 'data': data_arr}

服务器仍在打印 'I arrived here' 但会收到消息,直到与客户端的连接结束

您的循环将一直持续到客户端关闭连接为止。如果他们在收到您的回复之前不关闭,您就会陷入僵局。

因为您知道消息的长度,所以您可以在收到那么多字节后停止循环。

    received_length = 0
    while received_len < message_length:

        print("I arrived her")
        chunk = client_socket.recv(message_length - received_length)
        if not chunk:
            break
        fragments.append(chunk)
        received_length += len(chunk)