Created
March 21, 2011 05:00
-
-
Save minrk/879059 to your computer and use it in GitHub Desktop.
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
import os | |
import time | |
import json | |
import tornado.httpserver | |
import tornado.ioloop | |
import tornado.options | |
import tornado.web | |
from tornado.options import define, options | |
import zmq | |
from zmq.eventloop import ioloop, zmqstream | |
# hijack ioloop | |
tornado.ioloop.IOLoop = ioloop.IOLoop | |
ctx = zmq.Context() | |
sub = ctx.socket(zmq.SUB) | |
sub.setsockopt(zmq.SUBSCRIBE, b'') | |
sub.bind('tcp://*:5555') | |
define("port", default=8888, help="run on the given port", type=int) | |
class MainHandler(tornado.web.RequestHandler): | |
def get(self): | |
self.render('notebook.html') | |
class SUBHandler(tornado.web.RequestHandler): | |
@tornado.web.asynchronous | |
def get(self): | |
self.application.sub_stream.on_recv(self._really_get) | |
def _really_get(self, msg): | |
msgs = [msg] | |
self.application.sub_stream.on_recv(lambda m: msgs.append(m)) | |
self.application.sub_stream.flush() | |
self.application.sub_stream.stop_on_recv() | |
# write reply and finish | |
self.write(json.dumps(msgs)) | |
self.finish() | |
class NotebookApplication(tornado.web.Application): | |
def __init__(self, sub, loop): | |
self.sub_stream=zmqstream.ZMQStream(sub, loop) | |
self.loop = loop | |
handlers = [ | |
(r"/", MainHandler), | |
(r"/sub", SUBHandler) | |
] | |
settings = dict( | |
template_path=os.path.join(os.path.dirname(__file__), "templates"), | |
static_path=os.path.join(os.path.dirname(__file__), "static"), | |
) | |
tornado.web.Application.__init__(self, handlers, **settings) | |
def main(): | |
tornado.options.parse_command_line() | |
loop = tornado.ioloop.IOLoop.instance() | |
application = NotebookApplication(sub, loop) | |
http_server = tornado.httpserver.HTTPServer(application) | |
http_server.listen(options.port) | |
print loop | |
loop.start() | |
if __name__ == "__main__": | |
main() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment