Question

I want to communicate from a server to clients with a TCP server. My question regarding this is what I would do (resp. what would be a common method) to send bytes to a client from a different thread, e.g. when someone calls up a python script from the web. Is there any way to accomplish this?

Was it helpful?

Solution

You can define a member variable for the threads created when a client is connected. Then use a lock to write into this variable. This variable will be shared by all threads :

import threading

class ConnectedClients(threading.Thread):

    used_ressources = list()
    used_ressources_lock = threading.Lock()

    def run(self, ressource_to_get):
        if ressource_to_get in used_ressources:
            raise Exception('Already used ressource:' + repr(ressource_to_get))
        else:
            can_access = self.used_ressources_lock.acquire(blocking=True, timeout=5)
            if can_access:
                self.used_ressources.append(ressource_to_get)
                self.used_ressources_lock.release()
                # Do something...
                # You will have to acquire lock and remove ressource from
                # the list when you're done with it.
            else:
                raise Exception("Cannot acquire lock")

Is something like this that you are looking for ?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top