龙卷风长连接

时间:2014-03-05 07:28:23

标签: python tornado

我能否实现"长连接(持久连接,不长时间轮询)"使用tornado.web.RequestHandler?因为我需要包含连接,我需要接收"心脏消息"由客户端发送,所以,如果tornado.web.RequestHandler可以做到,我该怎么办?有这样的演示吗?

谢谢!

1 个答案:

答案 0 :(得分:2)

RequestHandler不适合这种情况,请改用WebSocketHandler。这是一个示例应用程序,每秒钟从每个客户端接收一次心跳:

import tornado.ioloop
import tornado.web
import tornado.websocket


class HeartBeatReceiver(tornado.websocket.WebSocketHandler):
    def open(self):
        pass

    def on_message(self, message):
        print message

    def on_close(self):
        pass


class Main(tornado.web.RequestHandler):
    def get(self):
        # This could be a template, too.
        self.write('''
<script>
function sendHeartBeat() {
    ws.send("heartbeat");
    setTimeout(sendHeartBeat, 1000);
}

ws = new WebSocket("ws://localhost:8888/websocket");
ws.onopen = sendHeartBeat;
</script>''')


application = tornado.web.Application([
    (r"/", Main),
    (r"/websocket", HeartBeatReceiver),
])

if __name__ == "__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()