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>
相关推荐
IpdataCloud19 分钟前
批量查IP的API接口怎么选?免费API配额瓶颈与离线库本地批量方案实测
网络·网络协议·tcp/ip
网络小江7 小时前
组网第33课:IP 地址与子网——CIDR、掩码、VLSM、网段规划与可用地址速算
网络协议·tcp/ip·子网掩码·vlsm·网络规划
山雀~7 小时前
WebSocket 断连之后:一次手机采集偶现卡死的排查与修复
网络·websocket·网络协议
码少女7 小时前
Linux——网络层-IP协议以及路由选择
linux·网络·网络协议·tcp/ip
砚底藏山河8 小时前
python量化:实时行情WebSocket断线重连状态机
java·python·websocket·金融
dsadas9 小时前
ospf宣告网段的理解
网络协议
爱研究的小梁10 小时前
从无人车配送走向集群联动作业,通信如何扛住协同压力?
网络·网络协议·机器人·信息与通信
hhb_61810 小时前
FastAPI接口开发与性能优化实战
性能优化·fastapi
汤愈韬11 小时前
OSPF的虚链路
网络·网络协议
honsor11 小时前
双网口 + RS485 机柜温湿度传感器,Modbus RTU/TCP 如何接入 Zabbix
网络协议·tcp/ip·zabbix