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>
相关推荐
F1FJJ11 小时前
Shield CLI Postgres v0.3.10:当 142 张表挤在一张 ER 图里,我们做了什么
网络·vscode·网络协议·postgresql·开源软件
TechWayfarer11 小时前
高并发场景下的IP归属地查询架构:从20ms到0.5ms的优化实践
网络协议·tcp/ip·架构
Hello_Embed11 小时前
嵌入式上位机开发入门(四):TCP 编程 —— Client 端实现
网络·笔记·网络协议·tcp/ip·嵌入式
电子科技圈14 小时前
Durin:Aliro标准赋能,打造无缝移动入户体验
人工智能·mcu·物联网·网络协议·智能家居·智能硬件·iot
曲幽16 小时前
FastAPI里玩转Redis和数据库的正确姿势,别让异步任务把你坑哭了!
redis·python·mysql·fastapi·web·celery·sqlalchemy·task·backgroundtask
TechWayfarer17 小时前
CDN智能调度实战:基于IP段归属查询实现电信/联通/移动流量分离(附Nginx Lua代码)
网络协议·tcp/ip·nginx
Vis-Lin17 小时前
BLE 协议栈:HCI ACL 数据详解
网络·物联网·网络协议·蓝牙·iot·ble
TechWayfarer17 小时前
攻防对抗:利用IP段归属查询快速定位攻击源并联动防火墙(iptables/UFW)自动封禁
网络·网络协议·tcp/ip
Srena量化员18 小时前
实时行情系统的第一道槛:如何应对数据源的“限流”与“断流”
websocket·实时行情
一个有温度的技术博主18 小时前
网安实验系列三:信息收集之Ip收集
网络·网络协议·tcp/ip