user2481309
user2481309

Reputation: 195

Convert tornado websocket object to json to identify the client

class ChatWebSocket(tornado.websocket.WebSocketHandler):
    clients = []
    def open(self):
        ChatWebSocket.clients.append(self)

        self.write_message(self)      
    def on_message(self, message):
        print(self)
        self.write_message('{"a":"SDF"}') 

    def on_close(self):
        ChatWebSocket.clients.remove(self)

I want to convert the self object in a json and send it to the client so that I can identify the request on_message and deliver the message to appropriate client.

Upvotes: 0

Views: 1500

Answers (1)

Paul Gladkov
Paul Gladkov

Reputation: 479

Actually you do something wrong. You don't need to convert self to json and send it to the client. Every instance of ChatWebSocket has information about its ws-connection. So method write_message send the message to appropriate client.

def write_message(self, message, binary=False):
    if isinstance(message, dict):
        message = tornado.escape.json_encode(message)
    self.ws_connection.write_message(message, binary=binary)

Upvotes: 1

Related Questions