Skip to content

Instantly share code, notes, and snippets.

@RussellLuo
Last active August 29, 2015 14:04
Show Gist options
  • Save RussellLuo/dffe7f4ed44a2aee7104 to your computer and use it in GitHub Desktop.
Save RussellLuo/dffe7f4ed44a2aee7104 to your computer and use it in GitHub Desktop.
An example showing how to use sockjs-tornado.
<script src="http://cdn.sockjs.org/sockjs-0.3.min.js"></script>
<script>
var sock = new SockJS('http://' + window.location.host + '/realtime-news');
sock.onopen = function() {
console.log('open');
};
sock.onmessage = function(e) {
console.log('message', e.data);
};
sock.onclose = function() {
console.log('close');
};
</script>
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import tornado.web
import tornado.ioloop
import sockjs.tornado
class IndexHandler(tornado.web.RequestHandler):
def get(self):
self.render('index.html')
class RealtimeNewsConnection(sockjs.tornado.SockJSConnection):
"""Publish realtime news."""
clients = set()
def on_open(self, info):
self.clients.add(self)
def on_message(self, message):
pass
def on_close(self):
self.clients.remove(self)
@classmethod
def publish(cls, message):
for client in cls.clients:
client.send(message)
if __name__ == '__main__':
# add urls of sockjs into tornado
RealtimeNewsRouter = sockjs.tornado.SockJSRouter(RealtimeNewsConnection,
'/realtime-news')
application = tornado.web.Application(
[(r'/', IndexHandler)] + RealtimeNewsRouter.urls
)
application.listen(8888)
tornado.ioloop.IOLoop.instance().start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment