Skip to content

Instantly share code, notes, and snippets.

@galenseilis
Created December 11, 2023 17:11
Show Gist options
  • Save galenseilis/b833123d3c93eec27a021a7e60052101 to your computer and use it in GitHub Desktop.
Save galenseilis/b833123d3c93eec27a021a7e60052101 to your computer and use it in GitHub Desktop.
socket_example.py
import socket
import pickle
data_structure = {'key': 'value', 'numbers': [1, 2, 3]}
# Serialize the data structure
serialized_data = pickle.dumps(data_structure)
# Send the serialized data to script2.py
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect(('localhost', 12345))
s.sendall(serialized_data)
# Receive the processed data from script2.py
received_data = s.recv(4096)
# Deserialize and print the processed data
processed_data = pickle.loads(received_data)
print("Processed data received from script2.py:", processed_data)
@galenseilis
Copy link
Author

Script2.py

import socket
import pickle

# Setup a socket to listen for incoming connections
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind(('localhost', 12345))
    s.listen()

    conn, addr = s.accept()
    with conn:
        print('Connected by', addr)

        # Receive the serialized data from script1.py
        serialized_data = conn.recv(4096)

        # Deserialize the data structure
        received_data = pickle.loads(serialized_data)

        # Process the data (for example, add 1 to each number in the list)
        processed_data = {'key': 'processed', 'numbers': [x + 1 for x in received_data['numbers']]}

        # Serialize and send the processed data back to script1.py
        serialized_processed_data = pickle.dumps(processed_data)
        conn.sendall(serialized_processed_data)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment