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 小时前
本地部署开源客服系统 FreeScout 并实现外部访问( Windows 版本)
运维·服务器·网络·windows·网络协议
你觉得脆皮鸡好吃吗1 小时前
Check Anti-CSRF Token (AI)
前端·网络·网络协议·安全·csrf·网络安全学习
小红的布丁6 小时前
IP、子网、私有地址、ARP 与 Ping 通信全过程
网络·网络协议·tcp/ip
海市公约8 小时前
FastAPI中间件与依赖系统实战指南
中间件·fastapi·依赖注入·异步编程·web架构·代码复用·拦截器模式
以太浮标8 小时前
华为eNSP综合实验之- 交换机组播VLAN(Multicast-VLAN)详细解析
运维·网络·网络协议·网络安全·华为·自动化·信息与通信
mounter6258 小时前
【深度解析】Device Memory TCP:开启高性能网络传输的“零拷贝”新时代
linux·服务器·网络·网络协议·tcp/ip·kernel·devmem
2501_921649498 小时前
2026 量化策略回测的历史数据 API:从数据获取到策略验证
websocket·金融·restful·量化·回测·api文档
KevinCyao9 小时前
彩信http接口如何接入?采用POST方式提交多媒体附件的彩信示例
网络·网络协议·http
常利兵9 小时前
从0到1:Spring Boot 中WebSocket实战揭秘,开启实时通信新时代
spring boot·后端·websocket
北京耐用通信9 小时前
破局工业通讯壁垒!耐达讯自动化EtherCAT转RS232网关,老设备焕新核心桥梁
服务器·网络·人工智能·科技·物联网·网络协议·自动化