Skip to content

Instantly share code, notes, and snippets.

@gregtap
Created February 28, 2015 04:32
Show Gist options
  • Save gregtap/8179de3a36d7e208b0c2 to your computer and use it in GitHub Desktop.
Save gregtap/8179de3a36d7e208b0c2 to your computer and use it in GitHub Desktop.
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sockjs-client/0.3.4/sockjs.min.js"></script>
</head>
<body>
<h1>SOCKJS demo</h1>
<script>
var sock = new SockJS("http://localhost:8888/live");
sock.onopen = function() {
console.log("open");
sock.send("test");
};
sock.onmessage = function(e) {
console.log("message", e.data);
};
sock.onclose = function() {
console.log("close");
};
</script>
</body>
</html>
import logging
import ujson
import tornado.ioloop
import tornado.web
from sockjs.tornado import SockJSConnection
from sockjs.tornado import SockJSRouter
from tornado.log import enable_pretty_logging
class LiveConnectionHandler(SockJSConnection):
def on_open(self, info):
self.authenticated = False
def on_message(self, message):
"""
"""
try:
ujson.loads(message)
except ValueError:
logging.error('Invalid JSON payload %s' % message)
self.close()
return
self.send(message)
def on_close(self,):
logging.debug("on close")
# create live router
LiveRouter = SockJSRouter(LiveConnectionHandler, '/live', {
'disabled_transports': ['htmlfile', 'eventsource',
'jsonp', 'xhr_streaming'],
'websocket_allow_origin': '*'
})
class StatsHandler(tornado.web.RequestHandler):
def get(self):
self.content_type = 'application/json'
self.write(ujson.dumps(LiveRouter.stats))
class Application(tornado.web.Application):
def __init__(self):
handlers = [(r'/stats/', StatsHandler)] + LiveRouter.urls
tornado.web.Application.__init__(self, handlers)
if __name__ == "__main__":
# set debug level
logging.getLogger().setLevel('DEBUG')
enable_pretty_logging()
# create Tornado app
app = Application()
app.listen(8888, '0.0.0.0')
tornado.ioloop.IOLoop.instance().start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment