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>
相关推荐
liulilittle3 小时前
TCP BBR 拥塞控制模块编译
网络·网络协议·tcp/ip
wangl_924 小时前
Modbus RTU 与 Modbus TCP 深入指南-功能码与数据模型
网络·网络协议·tcp/ip·tcp·modbus·rtu
wangl_925 小时前
Modbus RTU 与 Modbus TCP 深入指南-性能分析与优化
网络·网络协议·tcp/ip·tcp·modbus·rtu
源远流长jerry6 小时前
Linux 网络收包机制:从网卡到 Socket 的完整路径
linux·运维·服务器·网络·网络协议·tcp/ip
上海云盾安全满满7 小时前
选择接入高防IP后,源机是否还要带有防护
网络·网络协议·tcp/ip
Li emily7 小时前
用外汇实时api搭建多货币对波动率实时看板
python·api·fastapi
小李云雾8 小时前
实际代码操作知识点分析:SQLAlchemy+FastAPI + 异步MySQL 全流程解析 + 增删改查逐行注释
数据库·mysql·fastapi
treesforest8 小时前
IP地理位置精准查询:从城市级到街道级的定位技术深度解析
大数据·网络·网络协议·tcp/ip·安全·网络安全·ip
哼?~10 小时前
再谈UDP协议
网络·网络协议·udp
IPHWT 零软网络10 小时前
OM200G-A融合通信IP-PBX:国产化架构下的高可靠政企通信解决方案
网络协议·tcp/ip·架构