Home

Tags

Long-Polling with Tornado

2011-09-02 web tornado long_polling jquery

Пример асинхронного вызова long-polling на сервер tornado.

# coding:utf8

import tornado.httpserver
import tornado.ioloop
import tornado.web
import tornado.autoreload
import time

html = """<html>
<head>
    <script type="text/javascript" language="JavaScript"
        src="http://code.jquery.com/jquery-1.5.2.min.js"></script>
    <script type='text/javascript' language='JavaScript'>
        function test(){
            $.post('/longPolling',{},function(data){
                alert(data);
            });
        }
    </script>
</head>
<body>
    <input type="button" value="Test, wait 10 sec" onclick="test();"/>
</body>
</html>"""

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write(html)

class LongHandler(tornado.web.RequestHandler):
    @tornado.web.asynchronous
    def post(self):
        self.wait_for_smth(callback=self.async_callback(self.on_finish))

    def wait_for_smth(self, callback, t=10):
        if t:
            tornado.ioloop.IOLoop.instance().add_timeout(time.time() + 1,
                lambda: self.wait_for_smth(callback, t-1))
        else:
            callback()

    def on_finish(self):
        self.write("Long-Polling OK")
        self.finish()

if __name__ == "__main__":
    application = tornado.web.Application([
        (r"/", MainHandler),
        (r"/longPolling", LongHandler)
        ])
    tornado.autoreload.start()
    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

comments powered by Disqus