Skip to content

Instantly share code, notes, and snippets.

@newhouseb
Created May 5, 2011 06:23
Show Gist options
  • Save newhouseb/956631 to your computer and use it in GitHub Desktop.
Save newhouseb/956631 to your computer and use it in GitHub Desktop.
class CometConnections(tornado.web.RequestHandler):
connections = set({})
@tornado.web.asynchronous
def get(self):
CometConnections.connections.add(self)
def tell(self, js):
if self in CometConnections.connections:
CometConnections.connections.remove(self)
self.write(js)
self.finish()
@staticmethod
def tellall(js):
copy = set(CometConnections.connections)
for connection in copy:
try:
connection.tell(js)
except IOError:
if connection in CometConnections.connections:
CometConnections.connections.remove(connection)
clientside = """
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
function waitForMsg() {
// Simple long polling
$.ajax({
type: "GET", url: "/comet", async: true, cache: false, timeout: 50000,
success: function(data) { eval(data); waitForMsg(); },
error: function(XMLHttpRequest, textStatus, errorThrown) { if(textStatus != 'error') waitForMsg(); }
});
};
waitForMsg();
</script>""""
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write(clientside + whateverelsecode)
class IRCBot(threading.Thread):
def run(self):
while(1):
# irc bot stuff
CometConnections.tellall("$('iframe')[0].src = " + youtube_url)
application = tornado.web.Application([
(r"/", MainHandler),
(r"/comet", CometConnections),
])
if __name__ == "__main__":
irc = IRCBot()
irc.start()
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(8888)
tn = tornado.ioloop.IOLoop.instance()
try:
tn.start()
except KeyboardInterrupt:
irc.running = False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment