SockJS is the way to go: https://github.com/mrjoes/sockjs-tornado
First, make your environment ready:
pip install sockjs-tornado
Second, you have to setup Tornado:
application = django.core.handlers.wsgi.WSGIHandler()
container = tornado.wsgi.WSGIContainer(application)
tornado_app = tornado.web.Application(
EchoSockjsRouter('/websocket')+
[
('/source/([^/]+)', SourceHandler),
('.*', tornado.web.FallbackHandler, dict(fallback=container)),
]
)
HTTPServer(tornado_app).listen(port)
tornado.ioloop.IOLoop.instance().start()
'/source' is a Request handler (I use it for async with @gen.engine), '.*' works for Django, and EchoSockjsRouter is what you want:
from sockjs.tornado import SockJSRouter, SockJSConnection
class EchoWebSocket(SockJSConnection):
def on_open(self, request):
print "sockjs: open"
def on_message(self, data):
print "data: %r" % (data,)
self.send(data)
def on_comment(self, data):
print "data: %r" % (data,)
self.send(data)
def on_close(self):
print "sockjs: close"
def EchoSockjsRouter(prefix):
return SockJSRouter(EchoWebSocket, prefix).urls
After that, you will need to setup the UI (I am using SockJS client, version 0.3.4, http://sockjs.org, MIT License):
<script src="<SockJS Javascript>"></script>
<script>
socket = new SockJS('http://localhost:8000/websocket');
socket.onmessage = function(e) {
console.log(e.data);
};
socket.onclose = function() {
console.log('closed :(');
};
socket.onopen = function() {
console.log('opened :>');
letTheMadnessBegin();
};
function letTheMadnessBegin() {
// silly, but you get the idea
socket.send(JSON.stringify({
name: $('#name').text(),
message: $('input').val()
}));
}
<script>
Well, you can make the script pretty inside $(function(){})... but besides that, you are ready to go: http://grab.by/mSv6, http://grab.by/mSuU (sorry for the 404, it is to make it realistic O.o). I took this pattern from: https://idea.popcount.org/2012-09-21-django-with-sockjs/
Please note that I tried with Socketio, Tornado WebSocket and some others. However SocketJS was incredibly straight-forward.
Regards.