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>
相关推荐
2401_868534781 小时前
指令集-最常用 Linux 命令速查手册(整合版)
linux·网络协议
dog2503 小时前
再论 TCP 的流式传输
网络·网络协议·tcp/ip
喜欢吃燃面6 小时前
HTTP协议深度解析:从请求响应到状态管理与安全传输
linux·网络协议·学习
创新技术阁7 小时前
FastapiAdmin 前后端启动全流程详解
前端·后端·fastapi
傻啦嘿哟7 小时前
某宝商品爬虫:破解反爬的终极方案(含IP代理池+User-Agent轮换)
爬虫·网络协议·tcp/ip
典典分享指南7 小时前
飞书 + 企业微信 + 微信文档多端协同实践指南
汇编·flask·intellij-idea·fastapi
tyung11 小时前
znet 数据编解码:字节流怎么变成消息
后端·网络协议·go
鲨鱼辣钊12 小时前
FastAPI筑基_Day15_Alembic数据库迁移实战
数据库·elasticsearch·fastapi
Broccoli5230266512 小时前
FastAPI 中 Pydantic 模型与 SQLAlchemy ORM 模型的分工与转换规范
fastapi
头茬韭菜12 小时前
功能点 11-12:客户端、RPC 通信、监控与安全
网络协议·安全·rpc·fluss