'UnpicklingError on data received from socket

Context: I have a system with a server.py file and a live_client.py. Server is constantly updating an object. The system works correctly if I send the attributes of the object (which are numbers) via sockets (cliend.send(str(obj.attribute_to_send).encode('utf-8')).

Problem: After, I tried to send the object from the server with pickle client.send(pickle.loads(obj)). Problem occured when the the client tries to get the object back with pickle.loads(data_received). Error code: _pickle.UnpicklingError: pickle data was truncated.

server.py

async def stream_feed_clients():
    obj_gen = object_generator()
    global object
    global STREAM_CLIENTS
    async for obj in obj_gen:
        object = obj        
        for client in STREAM_CLIENTS: #STREAM_CLIENTS:Each time a client connects, another thread stores the client in this variable
            try:
                client.send(pickle.dumps(obj))
            except ConnectionResetError:
                client.close()
                print("Client disconnected!")
                STREAM_CLIENTS = set(filter(lambda x: x != client, STREAM_CLIENTS))

client.py

import socket, pickle, time

from CustomClass import MyClass

HOST = 'localhost'
PORT = XXXX
try:
    c = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    c.connect((HOST, PORT))
    message = {'client_type': 'LIVE'}
    print('Waiting')
    time.sleep(5)
    print('Sending')
    c.send(pickle.dumps(message)) # NOTE: This pickle works. It is used to notify the server this is a client that wants live data.
    print('Message sent')
    while True:
        data = c.recv(4096 * 32) # I've been trying with different buffer sizes.
        obj = pickle.loads(data) # ERROR OCCURS HERE: _pickle.UnpicklingError: pickle data was truncated
        print(obj.a)
except KeyboardInterrupt:
    print('Closing connection to server')
    c.close()
    print('Connection closed')
    print('Exiting...')
    exit()

Class code of object being sent

class MyClass:
    def __init__(self, a):
        self.a = a
    
    def get_a(self):
        return self.a


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source