Python Threaded TCP Socket Server Example

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:

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:

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:

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!