Question

In on_message() method of SockJS-Tornado library, I want to send JSON messages to clients: sometimes to specific clients using send() method, and sometimes to a group of clients using broadcast() method.

I wonder whether I need to use something like simplejson to encode string-keyed dictionary object myself before sending the message, i.e.

on_message(self, message):
    ...
    data = {'type': 1, 'body': 'blah'}
    msg = json.dump(data)
    # self.send(msg) or self.broadcast(conns, msg)

Or the encoding part is already taken care of by SockJS-Tornado? In addition, is it true that message argument in on_message() method is always also a JSON object?

Was it helpful?

Solution

SockJS is websocket emulation layer. Websockets don't support anything except of text and binary data.

So, while you can send arbitrary python object over the wire (sockjs-tornado will do internal json serialization and does not enforce strings), this is discouraged for compatibility reasons.

Yes, double encoding will happen if json is used as a application protocol. However, if you're going to have broadcast functionality - use optimized broadcast() method, it will do json-encoding only once for all recipients.

There was related discussion in mailing list as well: https://groups.google.com/forum/?fromgroups#!topic/sockjs/vsFvHqppq5g

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