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 小时前
算力机房多协议融合:Modbus TCP 温湿度变送器与 SNMP 设备混合组网方案
网络·网络协议·tcp/ip·传感器·温湿度
川石课堂软件测试3 小时前
涨薪技术|0到1学会性能测试第9课-HTTP响应统计
数据库·功能测试·网络协议·http·kubernetes·单元测试·测试用例
可信时间戳3 小时前
原创作品怎么申请版权?草稿、定稿、已发布、已授权,四个阶段四个做法
网络协议·http·https
话梅姐姐呀4 小时前
TCP/IP 架构各层的协议概述
人工智能·物联网·网络协议·tcp/ip·iot
husterlichf5 小时前
网关、掩码、子网、vlan、交换机
网络·网络协议
斌糖雪梨8 小时前
registerListeners(); 方法详解
网络·网络协议·rpc
福芯微电子有限公司nfc8 小时前
国产收音芯片 FSV4755:多波段调谐与高集成设计,赋能多种音频终端
网络协议·网络安全·音视频·信息与通信·信号处理
小天源1 天前
让访问数据可解释:IP 地球大屏、地区库更新与运行维护设计
网络·网络协议·tcp/ip
万年咸鱼1 天前
WebSocket、Socket 与 HTTP 的区别详解
websocket·网络协议·http
万年咸鱼1 天前
HTTPS 是如何保证传输安全的?
网络协议·安全·https