Created
August 6, 2013 14:26
-
-
Save agness/6164961 to your computer and use it in GitHub Desktop.
Tornado server that sends data to all clients ad infinitum.
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 tornado.httpserver | |
import tornado.ioloop | |
import tornado.options | |
import tornado.web | |
from random import randrange | |
import logging | |
from tornado.options import define, options | |
define("port", default=7777, help="run on the given port", type=int) | |
class MessageBuffer(object): | |
def __init__(self): | |
self.waiters = set() | |
def add(self, callback): | |
self.waiters.add(callback) | |
def remove(self, callback): | |
self.waiters.remove(callback) | |
def spit_all(self): | |
for callback in self.waiters: | |
callback() | |
m = MessageBuffer() | |
class MainHandler(tornado.web.RequestHandler): | |
@tornado.web.asynchronous | |
def get(self): | |
m.add(self.spit_msg) | |
def spit_msg(self): | |
s = str(randrange(10)) | |
logging.info("writing: "+s) | |
self.write(s+" ") | |
self.flush() | |
def on_connection_close(self): | |
m.remove(self.spit_msg) | |
def main(): | |
tornado.options.parse_command_line() | |
application = tornado.web.Application([ | |
(r"/", MainHandler), | |
]) | |
http_server = tornado.httpserver.HTTPServer(application) | |
http_server.listen(options.port) | |
main_loop = tornado.ioloop.IOLoop.instance() | |
scheduler = tornado.ioloop.PeriodicCallback(m.spit_all,300, main_loop) | |
scheduler.start() | |
main_loop.start() | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment