Dear fellow Python users,
I would need your help in figuring out how to send a continuous stream of data from an external environment to Processing via TCP. TCP is important because I need the data to remain intact and to arrive in the same order in which it was sent.
The idea is to be able to do some intensive computation task in a separate environment and to send the output (a list of coordinates, indices, …) in real time to Processing for rendering.
For this I am relying on Python socket
and pickle
modules. I can’t say if they are the most appropriate tools for this specific task so if you can think of a better alternative please let me know.
Tryout
Below a simple test script where I try to send the location of a point around a circle from a Jupyter Notebook. The location changes at each step of the loop and the corresponding coordinates are sent as a serialized tuple.
import socket
import pickle
import math
den = 20
rad = 100
theta = math.tau / den
HOST = "127.0.0.1"
PORT = 12000
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.connect((HOST, PORT)) #connect to server
for i in range(1000):
i = i%den
x = math.cos(i*theta) * rad
y = math.sin(i*theta) * rad
data = pickle.dumps((x, y), protocol=2) #protocol needs to be between 0 and 2 for Python 2
sock.send(data) #send data
On the Processing side , I have:
import socket
import pickle
HOST = "127.0.0.1"
PORT = 12000
def setup():
size(800, 800)
global s
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(2)
def draw():
background(255)
translate(width>>1, height>>1)
client, address = s.accept()
if client:
data = client.recv(4096)
print pickle.loads(data)
In order to get the transmission working the Processsing sketch must be launched prior to the Jupyter script.
Problem
I am only receiving the first coordinate of the loop (100.0, 0.0)
and nothing more. I also notice that client, address = s.accept()
breaks the draw()
function. It seems then to be stopped and only runs once when a TCP message is sent.
I can’t say for sure what is the reason of this behavior but my bet is that I am not correctly setting things on the server side (Processing sketch). I suspect the data to be sent entirely but not processed adequately on reception due to some mistakes that I am probably doing with the socket
module.
Would you mind helping me fixing this up ?