Login | Register 
FEATURES
APPLICATIONS
DOWNLOADS
EDUCATION
BLOG
WIKI
FORUM
STORE

Python Threaded TCP Socket Server Example

Helpful techniques for working with TouchDesigner. Answers only, no questions.

Python Threaded TCP Socket Server Example

Postby matthewwachter » Tue Apr 30, 2019 3:40 pm

I created this repo recently and thought some of you might find it useful for your projects. There are a lot of ways to create a stand-alone tcp socket server in python and a shitload of examples out there so it can be a bit difficult to figure out which is the best one to use or start from.

https://bitbucket.org/matthewwachter/tcp_threadedserver/src/master/

I use this particular example pretty often when we need to communicate to TD from a Flask app or really any python app/code that would be risky (or impossible) to run directly from TD.

If you were to send a message to it from TD you could use the TCP DAT and do something like this from a Text DAT:

Code: Select all
from datetime import datetime
import json

msg = {
   'cmd': 'test',
   'data': [str(datetime.now())],
}

msg = json.dumps(msg)

op('tcpip1').send(msg)


And then parse the incoming message in the callback script for the TCP DAT like so:
Code: Select all
import json

def onReceive(dat, rowIndex, message, bytes, peer):
   myjson = json.loads(message)
   
   cmd = myjson['cmd']
   data = myjson['data']
   
   print(cmd, data)
   return


One interesting thing I have noticed is that TD tends to add an extra byte on the end of the message (0x00). I'm a little unclear about why this would happen but I added this line in the server to help deal with that issue:

Code: Select all
data = loads(data.rstrip('\0'))


This example could be enhanced with the addition of a user provided callback function for the received client messages but I decided that it would be better not to overly complicate things. Later on I may add a different version for that.

Enjoy!
matthewwachter
 
Posts: 294
Joined: Fri Jul 08, 2011 3:18 pm
Location: Los Angeles

Return to Techniques

Who is online

Users browsing this forum: No registered users and 1 guest