tornado websocket實現後臺推送數據

1、長輪詢

一句話來概括:長輪詢就是客戶端和服務器端保持連接,相互發信息。

2、流程

  1. 前端發出一個請求。
  2. 後端接收到請求後,觸發on_message方法(執行write_message("hello"))。
  3. 前端收到“hello”觸發on_message方法(執行渲染,把hello渲染到頁面上)。
  4. 後端開始輪詢,向前端發消息。
  5. 前端接收到信息後不斷渲染新的內容。

3、代碼示例

3.1 handler

利用PeriodicCallback進行輪詢操作。 PeriodicCallback構造函數可以接收2個參數,一個是回調的函數,一個是間隔的時間。

class LastWeekTotalCarsHandler(WebSocketHandler):
    def init(self):
        self.last = time.time()
        self.stop = False

    def check_time(self):
        if time.time() - self.last > 10:
            today_total = get_last_week_total_cars(0)
            last_week_total = get_last_week_total_cars(-7)
            last_month_total = get_last_week_total_cars(-30)
            self.write_message(",".join([str(today_total), str(last_week_total), str(last_month_total)]))
            self.last = time.time()

    def open(self):
        """
        :return:
        """
        print("wedsocket opened")
        self.init()
        # PeriodicCallback構造函數可以接收2個參數,一個是回調的函數,一個是間隔的時間
        self.timer_loop = tornado.ioloop.PeriodicCallback(self.check_time,5000)
        self.timer_loop.start()

    def on_message(self, message):
        print("on message")
        today_total = get_last_week_total_cars(0)
        last_week_total = get_last_week_total_cars(-7)
        last_month_total = get_last_week_total_cars(-30)
        self.write_message(",".join([str(today_total), str(last_week_total), str(last_month_total)]))
        self.last = time.time()

    def close(self, code=None, reason=None):
        self.timer_loop.stop()

3.2前端

JavaScript:

<script type="text/javascript">
    var ws = new WebSocket("ws://127.0.0.1:8000/total_cars/");
    ws.onopen = function () {
        ws.send("Hello, world");
    };
    ws.onmessage = function (evt) {
        var today_total = document.getElementById("todaytotal");
        var last7total = document.getElementById("last7total");
        var last30total = document.getElementById("last30total");
        var arr = evt.data.split(",");
        today_total.innerHTML = arr[0];
        last7total.innerHTML =arr[1];
        last30total.innerHTML = arr[2];
    };
</script>

HTML:

<!-- ECharts -->
<div class="container">
    <!--    <div class="col-md-2"></div>-->
    <div class="col-md-9">
        <div id="zqhistogram" style="width: 600px;height:400px;"></div>
    </div>
    <div class="col-md-1" style="text-align: center;color: rgb(71,200,211)">
        <h5>今天總過車量</h5>
        <h2 id="todaytotal"></h2>
    </div>
    <div class="col-md-1" style="text-align: center;color: rgb(71,200,211)">
        <h5>近7天總過車量</h5>
        <h2 id="last7total"></h2>
    </div>
    <div class="col-md-1" style="text-align: center;color: rgb(71,200,211)">
        <h5>近30天總過車量</h5>
        <h2 id="last30total"></h2>
    </div>
</div>

4 展示

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章