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>
相关推荐
小灰灰搞电子1 分钟前
ESP32 使用ESP-IDF实现Modbus TCP主机通信源码分享
网络·modbustcp·网络协议·tcp/ip·esp32
五阿哥永琪1 小时前
HTTP包含哪些内容?
网络·网络协议·http
hoududubaba3 小时前
ORAN共享小区的级联FHM模式
网络·网络协议
yaoty4 小时前
Python日志存储:从单机同步到分布式异步的7种方案
fastapi·日志·logger
小飞大王6666 小时前
WebSocket技术与心跳检测
前端·javascript·websocket·网络协议·arcgis
星空椰6 小时前
FastAPI 进阶:中间件、依赖注入与 ORM
python·fastapi
码界筑梦坊6 小时前
220-基于Python的诺贝尔奖数据可视化分析系统
开发语言·python·信息可视化·数据分析·毕业设计·fastapi
我是Superman丶6 小时前
Nginx反向代理流式输出延迟?一招解决SSE/WebSocket缓冲问题SpringBoot+SSE流式输出卡住?Nginx这个配置必须关!
运维·websocket·nginx
一直都在5727 小时前
SpringBoot+Vue+Netty+WebSocket+WebRTC 实现视频聊天
vue.js·spring boot·websocket
hoududubaba7 小时前
ORAN中NB-IoT的基本概念
网络·网络协议