Skip to content

Instantly share code, notes, and snippets.

@agness
Created August 6, 2013 14:26
Show Gist options
  • Save agness/6164961 to your computer and use it in GitHub Desktop.
Save agness/6164961 to your computer and use it in GitHub Desktop.
Tornado server that sends data to all clients ad infinitum.
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