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 小时前
F12 Network:把“发 HTTP 请求”这件事变成看得见的东西
网络·网络协议·http
沫璃染墨1 小时前
从零入门计算机网络系列(五):UDP套接字编程实战——从核心API到客户端与服务器通信
linux·网络·c++·vscode·网络协议·udp
小马不起床1 小时前
零基础玩转 FastAPI_10:前端登录、权限与布局
前端·状态模式·fastapi
dadaobusi1 小时前
学习: flit vs tlp
网络·网络协议
paopaokaka_luck1 小时前
剧本杀预约管理系统(AI客服、 webSocket在线沟通、协同过滤算法推荐、Echarts多维分析、 QQ邮箱通知、 腾讯地图导航、四角色协作)
websocket·网络协议·echarts
ZeroNews内网穿透2 小时前
内网穿透公网暴露防护:边缘网关 IP 黑白名单运维实践
运维·网络协议·tcp/ip·内网穿透·api安全·企业网络安全·运维实践
honsor2 小时前
机房动环监控:以太网温湿度传感器选型与部署全解
运维·服务器·网络·物联网·网络协议·tcp/ip
honsor2 小时前
以太网温湿度传感器原理与 Modbus TCP 组网实战,机房动环监控落地
网络·嵌入式硬件·物联网·网络协议·tcp/ip
mingbaiceping3 小时前
复旦-华盛顿大学EMBA:2026年免联考申请条件详解
网络协议·https·ssl
网络小江3 小时前
上网第五十七课:60 天收官(上)——网络技术全景图回顾
网络协议