The TCP listener class I made here for listening to barcode scanners might be of some use. I was offloading to a queue for another script to chew through, you'll just be writing to a tag. I think there is also a listener server class in the thread somewhere, I was anticipating barcode scanners that acted as clients as well.
Further up in the post it talks about the storing of the old instance and killing it on script environment update/reset.