Search code examples
pythonsocketspuredata

How to send messages from Pure Data to Python?


I am trying to send messages from Pure Data to Python (to display on an SSD1306 OLED). Someone suggested I use sockets. They also provided the following Python code:

import socket
s = socket.socket()
host = socket.gethostname()
port = 3000

s.connect((host, port))
mess = "hello"
Msg = mess + " ;"
s.send(message.encode('utf-8'))

In Pure Data, a [netreceive 3000] object and a print object are connected together.

This works, but I want to do the exact opposite. Send data from Pure Data to Python using sockets. I found some tutorials but they all talked about Python to Python message receiving and sending. How can I implement Pd in that?


Solution

  • You can use Python's socket library to connect to a Pd patch that sends information through [netsend]. Here is a working minimal example. In Pd, create a simple patch that connects a [netsend] to a port on your localhost network:

    enter image description here

    Create and save a listener script in Python (adapted from here). The script below uses Python 3.6:

    import socket
    import sys
    
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_address = ('localhost', 13001)
    print(f'starting up on {server_address[0]} port {server_address[1]}')
    sock.bind(server_address)
    sock.listen(1)
    
    while True:
        print('waiting for a connection')
        connection, client_address = sock.accept()
        try:
            print('client connected:', client_address)
            while True:
                data = connection.recv(16)
                data = data.decode("utf-8")
                data = data.replace('\n', '').replace('\t','').replace('\r','').replace(';','')
                print(f'received {data}')
                if not data:
                    break
        finally:
            connection.close()
    

    Run this script, then run Pd's patch. Dragging that numberbox will send values to Python. In this example above, all received values are just printed with their labels:

    enter image description here

    You can then adapt these to your needs.