Pickle objects over network

Serializing python objects over network

Here is a way to use the pickle module to send objects like lists, dictionaries or any object over the network using tcp:

Beware unpickling from untrusted sources is dangerous as this could execute arbitary code if the sender is malicious. In our example below it’s not an issue.

Server code:

# tcp server: serializing python objects over network
import socket, pickle

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
host = 'localhost'
port= 4444
s.bind( (host, port) )
s.listen(1)
conn, addr = s.accept()
try:
    #must be sure that object fits in 1024 bytes
    L = pickle.loads(conn.recv(1024))
    print(f'{addr[0]} sends object of type  {type(L)}')
    print(L)
    L.append({'a':3, 'c':9})
    data=pickle.dumps(L)
    conn.sendall(data)
except pickle.UnpicklingError:
    print('Error: 1024 bytes read buffer is too small.Increase buffer size')
finally:
    conn.close()

Client code:

#tcp client: serializing python objects over network
import socket, pickle

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = 'localhost'
port = 4444
s.connect( (host, port) )

L=[('B','N'), (3,5), 'the end', (1.4,2.3,3.0)]
data = pickle.dumps(L)
s.sendall(data)
try:
    L2 = pickle.loads(s.recv(1024))
    print('Server sends modified list:')
    print(L2)
except pickle.UnpicklingError:
    print('Error: 1024 bytes read buffer is too small. Increase buffer size')
finally:
    s.close()