Sep-27-2022, 09:35 AM
(This post was last modified: Sep-27-2022, 09:35 AM by Gribouillis.)
DPaul Wrote:you end up with 2... objects in the same pickle file.Here is an example of this feature with sockets: A client connects to a server and sends three Python objects by successive calls to pickle.dump() in the same file-like object. The server receives the Python objects and prints them.
Server code:
# pickserver.py import pickle import socket import sys # Create a TCP/IP socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # Bind the socket to the port server_address = ('localhost', 10000) print('starting up on {} port {}'.format(*server_address)) sock.bind(server_address) # Listen for incoming connections sock.listen(1) while True: # Wait for a connection print('waiting for a connection') connection, client_address = sock.accept() try: print('connection from', client_address) connection.shutdown(socket.SHUT_WR) file = connection.makefile(mode='rb') unpic = pickle.Unpickler(file) # Receive Python objects and print them while True: try: obj = unpic.load() except EOFError: break else: print(f'received: {repr(obj)}') finally: # Clean up the connection connection.close()Client code:
# pickclient.py import pickle import socket import sys # Create a TCP/IP socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Connect the socket to the port where the server is listening server_address = ('localhost', 10000) print('connecting to {} port {}'.format(*server_address)) sock.connect(server_address) sock.shutdown(socket.SHUT_RD) file = sock.makefile(mode='wb') pick = pickle.Pickler(file) try: # Send Python objects data = [ 10, [2, 'spam', 'eggs'], (5, 7, 11), ] for obj in data: print(f'sending: {repr(obj)}') pick.dump(obj) finally: print('closing socket') sock.close()Output on the server side:
Output:λ python paillasse/pf/pickserver.py
starting up on localhost port 10000
waiting for a connection
connection from ('127.0.0.1', 34014)
received: 10
received: [2, 'spam', 'eggs']
received: (5, 7, 11)
waiting for a connection
Output on the client sideOutput:λ python paillasse/pf/pickclient.py
connecting to localhost port 10000
sending: 10
sending: [2, 'spam', 'eggs']
sending: (5, 7, 11)
closing socket