使用websockets,后台实时发数据,前台实时接受数据,并集成到Django

后端代码

#!/usr/bin/env python

# WS server that sends messages at random intervals

import asyncio
import websockets
import time
import random
import json
from datetime import datetime


async def my_test(websocket, path):
    while True:
        camera_ip = '10.192.49.1'
        server_ip = '10.193.33.139'
        server_port = '8000'

        a = random.randint(1000, 10000)
        b = random.randint(10, 200)
        c = random.randint(20, 40)
        numlist = [a, b, int(a/b), c]

        worklist = []
        for i in range(10):
            id = i
            time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            count = random.randint(20, 40)
            path = "./html/results/test.jpg"
            worklist.append([id, time, count, path])

        daycount = random.randint(30, 200)
        nightcount = random.randint(30, 200)
        dayratio = int((daycount / (daycount + nightcount)) * 100)
        nightratio = 100 - dayratio
        daynight = [[dayratio, daycount], [nightratio, nightcount]]

        real_time_img = "static/results/test11.jpg"
        recognize_result_img = "static/results/test22.jpg"
        save_origine_img = "static/results/test33.jpg"

        return_dict = dict(server_ip=server_ip,
                           server_port=server_port,
                           camera_ip = camera_ip,
                           numlist=numlist,
                           worklist=worklist,
                           real_time_img=real_time_img,
                           recognize_result_img=recognize_result_img,
                           save_origine_img=save_origine_img,
                           daynight = daynight)
        return_dict = json.dumps(return_dict)

        await websocket.send(return_dict)
        await asyncio.sleep(1)

async def main():
    async with websockets.serve(my_test, "10.193.33.139", 1234):
        await asyncio.Future()

asyncio.get_event_loop().run_until_complete(main())

前端代码:

 <script type="text/javascript">var websocket = new WebSocket("ws://10.193.33.139:1234");
  //连接成功建立的回调方法
  // websocket.onopen = function () {
  //     window.alert('连接成功')
  // };
  // 前端接收后端传来的消息
  websocket.onmessage = function(event) {

    var infodic = JSON.parse(event.data);

    document.getElementById('server_IP').innerText = "服务器IP: " + infodic.server_ip;
    document.getElementById('server_port').innerText = "服务器端口:" + infodic.server_port;
    document.getElementById('camera_IP').innerText = "摄像头IP:" + infodic.camera_ip;

    // 设置数字
    document.getElementById('num1').innerText = infodic.numlist[0];
    document.getElementById('num2').innerText = infodic.numlist[1];
    document.getElementById('num3').innerText = infodic.numlist[2];
    document.getElementById('num4').innerText = infodic.numlist[3];

    // 设置图片
    document.getElementById('real_time_img').setAttribute("src", infodic.real_time_img) document.getElementById('real_time_img_light').setAttribute("src", infodic.real_time_img) document.getElementById('recognize_result_img').setAttribute("src", infodic.recognize_result_img) document.getElementById('recognize_result_img_light').setAttribute("src", infodic.recognize_result_img) document.getElementById('save_origine_img').setAttribute("src", infodic.save_origine_img) document.getElementById('save_origine_img_light').setAttribute("src", infodic.save_origine_img)

    // 设置表格
    for (var i = 0; i < 9; i++) {
      document.getElementById('work_id_' + (i + 1)).innerText = infodic.worklist[i][0];
      document.getElementById('work_time_' + (i + 1)).innerText = infodic.worklist[i][1];
      document.getElementById('work_count_' + (i + 1)).innerText = infodic.worklist[i][2];
      document.getElementById('work_save_' + (i + 1)).innerText = infodic.worklist[i][3];
    }

    // 设置扇形图
    jQuery(document).ready(function($) {
      var donut_chart_demo = $("#donut-chart-demo");
      donut_chart_demo.empty() donut_chart_demo.parent().show();
      var donut_chart = Morris.Donut({
        element: 'donut-chart-demo',
        data: [{
          label: "白天纸浆总量(" + infodic.daynight[0][0] + "%)",
          value: infodic.daynight[0][1]
        },
        {
          label: "夜晚纸浆总量(" + infodic.daynight[1][0] + "%)",
          value: infodic.daynight[1][1]
        }],
        colors: ['#707f9b', '#242d3c']
      });
      donut_chart_demo.parent().attr('style', '');
    });

  };
  //连接关闭的回调方法
  websocket.onclose = function() {
    websocket.close();
    // window.alert('连接已断开或未连接')
  };
  //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
  window.onbeforeunload = function() {
    websocket.close();
  };
  //关闭连接
  function closeWebSocket() {
    websocket.close();
    // window.clearInterval(intervalId);
  }
</script>

 

集成到Django的manage.py 文件时,后端代码:

#!/usr/bin/env python

# WS server that sends messages at random intervals

import asyncio
import websockets
import random
import json
import threading
from datetime import datetime


async def runner(websocket, path):
    while True:
        camera_ip = '10.192.49.1'
        server_ip = '10.193.33.139'
        server_port = '8000'

        a = random.randint(1000, 10000)
        b = random.randint(10, 200)
        c = random.randint(20, 40)
        numlist = [a, b, int(a/b), c]

        worklist = []
        for i in range(10):
            id = i
            time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            count = random.randint(20, 40)
            path = "./html/results/test.jpg"
            worklist.append([id, time, count, path])

        daycount = random.randint(30, 200)
        nightcount = random.randint(30, 200)
        dayratio = int((daycount / (daycount + nightcount)) * 100)
        nightratio = 100 - dayratio
        daynight = [[dayratio, daycount], [nightratio, nightcount]]

        real_time_img = "static/results/test11.jpg"
        recognize_result_img = "static/results/test22.jpg"
        save_origine_img = "static/results/test33.jpg"

        return_dict = dict(server_ip=server_ip,
                           server_port=server_port,
                           camera_ip = camera_ip,
                           numlist=numlist,
                           worklist=worklist,
                           real_time_img=real_time_img,
                           recognize_result_img=recognize_result_img,
                           save_origine_img=save_origine_img,
                           daynight = daynight)
        return_dict = json.dumps(return_dict)

        await websocket.send(return_dict)
        await asyncio.sleep(1)


async def main():
    async with websockets.serve(runner, "10.193.33.139", 1234):
        await asyncio.Future()


class MyThread (threading.Thread):
    def __init__(self, threadID, name):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        
    def run(self):
        print("开始线程:" + self.name)
        # loop = asyncio.get_event_loop().run_until_complete(main())
        # asyncio.set_event_loop(loop)
        asyncio.set_event_loop(asyncio.new_event_loop())
        loop = asyncio.get_event_loop()
        loop.run_until_complete(main())
        print("退出线程:" + self.name)
        

def myApplication():
    thread = MyThread(1, "Thread-1")
    thread.start()

 

当出现以下错误时:

RuntimeError: There is no current event loop in thread 'Thread-1'.

在调用协程语句前加入下述语句即可解决:

asyncio.set_event_loop(asyncio.new_event_loop())

参考:Tornado5 执行线程时报错:RuntimeError: There is no current event loop in thread 'Thread-1'._jusang486的专栏-CSDN博客icon-default.png?t=LA23https://blog.csdn.net/jusang486/article/details/82382358 (1条消息) python协程系列(六)——asyncio的EventLoop以及Future详解_MIss-Y的博客-CSDN博客icon-default.png?t=LA23https://blog.csdn.net/qq_27825451/article/details/86292513

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值