websocket在django框架中的使用

asgi.py

import os
from django.core.asgi import get_asgi_application
from .websocket import websocket_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'process_management.settings')
http_application = get_asgi_application()


async def application(scope, receive, send):
    if scope['type'] == 'http':
        await http_application(scope, receive, send)
    elif scope['type'] == 'websocket':
        await websocket_application(scope, receive, send)
    else:
        raise Exception('unkown scope type', + scope['type'])

websocket.py

import os
import subprocess
import psutil


async def websocket_application(scope, receive, send):
    while True:
        event = await receive()
        # 收到建立websocket 连接的消息
        if event['type'] == 'websocket.connect':
            await send({
    
    'type': 'websocket.accept'})
        # 收到中断连接的消息
        elif event['type'] == 'websocket.disconnect':
            break
        # 其他情况,正常的websocket消息
        elif event['type'] == 'websocket.receive':
            if event['text'] == 'process':
                pid = os.getpid()
                process = psutil.Process(pid=pid)
                process = process.parent()
                name = process.name()
                cpu_usage = process.cpu_percent()
                memory_usage = process.memory_full_info().uss
                threads_number = process.num_threads()
                status = process.status()
                await send({
    
    
                    'type': 'websocket.send',
                    'text':
                        f"pid:{pid},name:{name},cpu_usage:{cpu_usage},memory_usage:{memory_usage},threads_number:{threads_number},status:{status}"
                })
            elif event['text'] == 'gpu':
                info = subprocess.run(
                    "nvidia-smi dmon -c 1",
                    shell=True, stdout=subprocess.PIPE
                ).stdout.decode()
                info_list = info.splitlines()[-1].split()
                await send({
    
    
                    'type': 'websocket.send',
                    'text':
                        f" gpu: {info_list[0]} \n pwr: {info_list[1]},gtemp:{info_list[2]},mtemp: {info_list[3]}"
                        f" sm: {info_list[4]},mem: {info_list[5]},enc: {info_list[6]},dec:{info_list[7]},mclk:{info_list[8]},pclk:{info_list[9]}"
                })
            elif event['text'] == 'server':

                cpu_percent = psutil.cpu_percent()
                memory_total = psutil.virtual_memory().total
                memory_available = psutil.virtual_memory().available
                disk_total = psutil.disk_usage("/").total
                disk_free = psutil.disk_usage("/").free
                await send({
    
    
                    'type': 'websocket.send',
                    'text': f"cpu_percent:{cpu_percent},memory_total:{memory_total},memory_available:{memory_available},disk_total:{disk_total},disk_free:{disk_free}"
                })

        else:
            raise Exception('Connect Error')
    print("[disconnect]")

前端js

<script>
        var ws_url = 'ws://0.0.0.0:8000';
        // var ws_url = window.location.host;
        console.log(ws_url);
        var ws = new WebSocket(ws_url);

        //建立websocket连接
        ws = new WebSocket(ws_url);
        //定义事件
        ws.onopen = function (e){
     
     
            console.log('websocket 建立连接成功');
            // alert("websocket 建立连接成功")
        }
        ws.onmessage = function (e){
     
     
            console.log('websocket收到消息:', e.data);
            alert(e.data);
        }
        ws.onclose = function (e){
     
     
            console.log('websocket 连接中断');
            // alert("websocket 连接中断 请检查工程!")
        }
        ws.onerror = function (e){
     
     
            console.log('websocket错误',e);
            alert(e);
        }
        function ws_send(text){
     
     
            ws.send(text)
        }

    </script>

django目录层级
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_46248273/article/details/118326025
今日推荐