vue2使用websocket和echars动态展示本机CPU使用情况,后端框架使用fastapi

后端代码:

python 复制代码
from fastapi import FastAPI, WebSocket
import psutil
import asyncio

app = FastAPI()

@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    while True:
        cpu_usage = psutil.cpu_percent(interval=1)  # 获取 CPU 使用率
        await websocket.send_json({"cpu_usage": cpu_usage})
        await asyncio.sleep(1)  # 每秒发送一次数据

后端运行:
uvicorn main:app --port 9999

前端代码:

安装插件
npm install echarts

vue 复制代码
<template>
  <div>
    <div id="cpu-chart" style="width: 600px;height:400px;"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts';

export default {
  data() {
    return {
      chart: null,
      ws: null,
      data: [],
    };
  },
  mounted() {
    this.initWebSocket();
    this.initChart();
  },
  methods: {
    initWebSocket() {
      this.ws = new WebSocket('ws://localhost:9999/ws');
      this.ws.onmessage = (event) => {
        const message = JSON.parse(event.data);
        this.updateChartData(message.cpu_usage);
      };
    },
    initChart() {
      this.chart = echarts.init(document.getElementById('cpu-chart'));
      const option = {
        title: {
          text: 'CPU Usage',
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
          },
        },
        xAxis: {
          type: 'category',
          data: [],
        },
        yAxis: {
          type: 'value',
          min: 0,
          max: 100,
          axisLabel: {
            formatter: '{value} %',
          },
        },
        series: [
          {
            name: 'CPU Usage',
            type: 'line',
            data: this.data,
          },
        ],
      };
      this.chart.setOption(option);
    },
    updateChartData(cpuUsage) {
      const now = new Date();
      const time = `${now.getHours()}:${now.getMinutes()}:${now.getSeconds()}`;
      this.data.push(cpuUsage);
      this.chart.setOption({
        xAxis: {
          data: [...Array(this.data.length).keys()].map(i => `#${i + 1}`),
        },
        series: [{
          data: this.data,
        }],
      });
    },
  },
  beforeDestroy() {
    if (this.ws) {
      this.ws.close();
    }
  },
};
</script>

<style>
/* Your CSS here */
</style>
相关推荐
码农爱学习6 分钟前
使用wpa工具配网、udhcpc分配IP的过程分析
网络·网络协议·tcp/ip
北京耐用通信1 小时前
协议转换的‘魔法转换器’!耐达讯自动化Ethernet/IP转Devicenet如何让工业机器人‘听懂’不同咒语?”
网络·人工智能·科技·网络协议·机器人·自动化·信息与通信
CAir23 小时前
一问读懂并了解HTTP代理的基本原理
网络·网络协议·http·代理
北京耐用通信3 小时前
阀岛的“超级大脑”:耐达讯自动化网关让EtherNet/IP转DeviceNet“说同一种语言”
人工智能·物联网·网络协议·网络安全·自动化·信息与通信
卓码软件测评3 小时前
具有CMA和CNAS双重资质的软件测试机构【Gatling脚本开发资源请求处理:html、css、js自动下载配置】
websocket·网络协议·测试工具·单元测试·测试用例
喜欢流萤吖~5 小时前
POST 与 GET:HTTP 请求方法的本质区别
网络·网络协议·http
宋拾壹5 小时前
物理服务器映射端口
网络协议·ssl
Tandy12356_6 小时前
手写TCP/IP协议栈——ARP输入处理
c语言·网络协议·tcp/ip·计算机网络
涡轮蒸鸭猫喵6 小时前
-------------------UDP协议+TCP协议-------------------------
java·网络·笔记·网络协议·tcp/ip·udp
wu_dangwangye7 小时前
n8n,make,Zapier自动化工作流速成教学
python·fastapi