当前位置: 代码迷 >> 综合 >> tornado websocket实现后台推送数据
  详细解决方案

tornado websocket实现后台推送数据

热度:71   发布时间:2023-12-28 13:20:02.0

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 = Falsedef 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 展示

 

  相关解决方案