Skip to content Skip to sidebar Skip to footer

Python Tornado Send Websocket Messages From Another Thread

I want to use WebSockets in Python to keep web clients up to date about data that I am reading from a serial port using PySerial. I am currently using the following code to read th

Solution 1:

Reading the official documentation for using asyncio and multithreading together at https://docs.python.org/3/library/asyncio-dev.html#asyncio-multithreading gave me the necessary clue that one can achieve this quite elegantly using the "call_soon_threadsafe" function. The following code thus seems to do the trick

tornado.ioloop.IOLoop.configure("tornado.platform.asyncio.AsyncIOLoop")
io_loop = tornado.ioloop.IOLoop.current()
asyncio.set_event_loop(io_loop.asyncio_loop)

clients = []

defbcint(message):
    for client in clients:
        client.write_message(message)
        print("broadcasted")

defBroadcast(message):
    io_loop.asyncio_loop.call_soon_threadsafe(bcint, message)

worker.broadcast = Broadcast

classWSHandler(tornado.websocket.WebSocketHandler):
    defopen(self):
        print('new connection')
        clients.append(self)
      
    defon_message(self, message):
        print('message received:  %s' % message)
        response = handler.HandleRequest(message, self.write_message)
 
    defon_close(self):
        print('connection closed')
        clients.remove(self)
 
    defcheck_origin(self, origin):
        returnTrue
 
application = tornado.web.Application([
    (r'/ws', WSHandler),
])
 
if __name__ == "__main__":
    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(8765)
    myIP = socket.gethostbyname(socket.gethostname())
    print('*** Websocket Server Started at %s***' % myIP)
    tornado.ioloop.IOLoop.current().start()

Solution 2:

One cleaner option is to use queues such as pyzmq that will help you establish communication from one thread to another.

Looking at your use case, you can use PUB/SUB model. Here is a sample code. Also, you can use 'inproc' instead of 'tcp'. This will reduce the latency since you will be communicating between multiple threads in same process.

Post a Comment for "Python Tornado Send Websocket Messages From Another Thread"