In Tornado implementation of Websocket one needs to use WebSocketHandler a subclass of a RequestHandler for handling communication with websocket clients. Example in the docs demonstrate how to write a message back to the client in a response to their message, but the documentation does not make it clear what is the right way to implement broadcasting to the clients which did not participate in the exchange (for instance to all active clients).
How should one go about broadcasting a message to all actively connected websocket clients in tornado.websocket? I posted my current approach as one of the answers.
Solution I am using now was mentioned in a slightly related question and also used in one chat example. I would like to learn however if there is a better way, or if this one is indeed how it should be done.
EDIT1: Another related question using the same approach: Broadcasting a message using Tornado
One way I found but I am not sure if this is how one should really go about it is just adding the WebSocketHandler to a globally list in open:
active_clients = set()
class Handler(WebSocketHandler):
def open(self):
active_clients.add(self)
def on_message(self, args):
for client in active_clients:
client.write_message('msg') # will be written to every client
def on_close(self):
active_clients.remove(self)