A
A
Alikhan2021-10-25 09:42:53
Python
Alikhan, 2021-10-25 09:42:53

How to fix error when passing array via socket and pickle in Python?

I wanted to transfer an array through sockets in Python every time when receiving data from the server, that is, the client connects to the server and receives an array, the array in the server was wrapped in pickle.dumps, and in the client we receive an array using pickle.loads, but this causes an error .

Server code:

import socket
import pickle

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(("127.0.0.1", 5467))

class Parser:
    pass

citys = ["Moscow", "New-York", "Paris", "London", "Chikago"]

if __name__ == "__main__":
    server.listen()

    parser = Parser()
    data = pickle.dumps([citys, parser])

    while True:
        user, address = server.accept()
        user.send(data)


Client code:
import socket
import pickle

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(("127.0.0.1", 5467))

new_data = client.recv(65507)
data = pickle.loads(new_data)

print(data)


But it gives this error:
Traceback (most recent call last):
  File "C:\Users\123\Desktop\client.py", line 8, in <module>
    data = pickle.loads(new_data)
AttributeError: Can't get attribute 'Parser' on <module '__main__' from 'C:\\Users\\123\\Desktop\\client.py'>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
kamenyuga, 2021-10-25
Mulaev @AlikhanPython

Pickle stores objects and data type references (names of classes and functions), but not their definitions. You can fix the error in different ways.
1. Manually save the definition of the class as well.
2. Make methods for saving/loading objects into standard data types or text in the class.
3. Use libraries that serialize more data at once, for example, dill.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question