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>
相关推荐
张赐荣10 小时前
sslx: 一个检测、查看 HTTPS 证书信息的跨平台单文件命令行工具
网络协议·http·https
辛迪聊物业数字化10 小时前
物业费收缴率从68%提升到97%落地复盘:中小物业收费系统选型避坑指南
人工智能·嵌入式硬件·物联网·网络协议·系统架构
80s77711 小时前
态住宅IP在跨境电商防关联中的技术应用
网络·网络协议·tcp/ip
XiYang-DING11 小时前
【WebSocket】文本帧Text Frame
网络·websocket·网络协议
Novproxy_Z11 小时前
代理 IP 黑白名单体系搭建:自动标记风控 IP,减少封号
网络·网络协议·tcp/ip
RacentCLM11 小时前
HTTPS只在登录时有用?关于TLS的误解讲清
数据库·网络协议·https
雪雪爱冲浪11 小时前
用 Kimi 做网页抓取:从零开始的科普指南
网络协议
又蓝11 小时前
【元宝搜索开发者征文大赛】用 FastAPI + Vue3 做了个 AI 炒股工具,接了六个分析师和腾讯元宝搜索
人工智能·python·ai·fastapi
外收内放12 小时前
FastAPI猜字谜实战(8):收官
开发语言·python·学习·fastapi
洋不写bug13 小时前
HTTP(二):万字解析HTTP交互的请求、响应报文格式
网络协议·http·交互·postman·请求格式·响应格式·restful规范