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>
相关推荐
初学AI的小高3 小时前
FastAPI 工程实践:LLM 应用的 API 设计之道
后端·fastapi
java1234_小锋4 小时前
FastAPI python web开发- 中间件
fastapi
paopaokaka_luck5 小时前
基于Springboot3+vue3的旅游景区点评系统(AI审核、webSocket聊天、协同过滤算法、Echarts图形化分析)
websocket·网络协议·旅游
不能只会打代码6 小时前
Day 002 — Python 工程化 & FastAPI & 数据库速通
数据库·redis·python·docker·fastapi·测试
zhiSiBuYu05177 小时前
FastAPI 结合 Jinja2 模板开发入门指南
fastapi
熬夜苦读学习7 小时前
基于websocket的多用户五子棋网页游戏
linux·服务器·网络·websocket·网络协议·游戏·五子棋
allnlei9 小时前
React + FastAPI 前后端分离架构下的 Nginx 配置实践
react.js·架构·fastapi
广州灵眸科技有限公司9 小时前
xfce桌面旋转说明:基于灵眸科技EASY-EAI-Nano-TB
网络·网络协议·tcp/ip·算法·php
GlobalSign数字证书10 小时前
ACME 的 HTTP 验证和 DNS 验证,哪种更适合自动续期?
网络·网络协议·http
微硬创新10 小时前
耐达讯自动化PROFINET转DeviceNet网关:医药包装生产线的合规与效率双保障
服务器·人工智能·物联网·网络协议·自动化·信息与通信