[Solved] Tornado – Listen to multiple clients simultaneously over websockets

I want to use Tornado for creating a websocket server in Python. Here is the API: http://tornado.readthedocs.org/en/latest/websocket.html

In the APIs, I do not see an option to get a handle for the client. How do I handle multiple client connections at the same time?
For example, on_message(self, message) method directly gives the message. Doesn’t contain any handle for the client who has connected.
I would want to receive client requests, do some processing (which might take a long time), and then reply back to the client. I am looking for a client handle which I can use to reply back at a later time.

Enquirer: Vishal

||

Solution #1:

As I understand you want something like this:

class MyWebSocketHandler(tornado.websocket.WebSocketHandler):
    # other methods
    def on_message(self, message):
        # do some stuff with the message that takes a long time
        self.write_message(response)

Every websocket connection has its own object from your subclassed WebSocketHandler.

You can even save the connection and use it elsewhere:

ws_clients = []

class MyWebSocketHandler(tornado.websocket.WebSocketHandler):
    # other methods
    def open(self):
        if self not in ws_clients:
            ws_clients.append(self)

    def on_close(self):
        if self in ws_clients:
            ws_clients.remove(self)

def send_message_to_all(self, message):
    for c in ws_clients:
        c.write_message(message)
Respondent: gre_gor

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.