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>
相关推荐
FlightYe8 小时前
音视频修炼之容器与协议(七):HTTP-MP4 / HTTP-FLV
linux·网络·网络协议·http·ffmpeg·音视频
用户849137175471610 小时前
抄来的 SNMP4J 代码能跑,却把"没回执"记成了"值为 0"——一次 GET 到底该怎么采对?
网络协议
知识汲取者13 小时前
HTTP、SSE、WebSocket:三个老技术的区别、场景与选型
websocket·http·ai
ShineWinsu15 小时前
对于Qt:TCP的解析
linux·c++·qt·网络协议·面试·tcp·客户端
郝学胜-神的一滴17 小时前
Effective Python 条款45:巧用属性注解平滑升级类属性
运维·开发语言·数据库·python·网络协议·numpy
SEO_juper17 小时前
HTTPS 混合内容检查工具:页面全站 https 了,但还有 http 资源在拖后腿
开发语言·网络协议·http·https·node.js·json·bash
王亚博_Abel2 天前
域名是怎么变成 IP 的?手拆 DNS 解析四个实验实测
网络·网络协议·tcp/ip
用户84913717547162 天前
两版 SNMP 报文只差 1 个字节,我盯了半天才看懂问题出在哪
网络协议
AndreaYYmm2 天前
SIGUSR2 触发热重载:一个正在抓包的进程如何原子地换掉规则集
c语言·网络协议
用户84913717547162 天前
为什么 SNMP 叫"简单"?真相是:设备少干活,复杂全甩给了你
网络协议