Last active
August 29, 2015 14:04
-
-
Save RussellLuo/dffe7f4ed44a2aee7104 to your computer and use it in GitHub Desktop.
An example showing how to use sockjs-tornado.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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