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>
相关推荐
wangl_928 小时前
Modbus RTU 与 Modbus TCP 深入指南-附录:快速参考表
网络·网络协议·tcp/ip·tcp·modbus·rtu
wangl_9210 小时前
Modbus RTU 与 Modbus TCP 深入指南-决策树与选型建议
网络·网络协议·tcp/ip·tcp·modbus·rtu
狐狐生风11 小时前
LangGraph 生产级部署全解:FastAPI + Docker
python·docker·langchain·prompt·fastapi·langgraph·agentai
码以致用11 小时前
FastAPI 从入门到实践:构建规范的 RESTful API 服务
后端·restful·fastapi
小船跨境11 小时前
ChatGPT助力高效网页数据抓取实战
人工智能·网络协议
Kiyra11 小时前
Query Rewrite 不是越智能越好:RAG 检索的精确词保护与动态召回
redis·websocket·junit·单元测试·json
JiaWen技术圈12 小时前
DTLS 基础
网络协议
m0_7381207213 小时前
ctfshow靶场SSRF部分——基础绕过到协议攻击解题思路与技巧(二)
python·网络协议·tcp/ip·安全·网络安全
Ogcloud_oversea13 小时前
SD-WAN 技术架构解析:控制平面与数据平面的解耦实践
运维·网络·网络协议·网络安全·信息与通信
树下水月14 小时前
HTTPS 站点请求 HTTP的API 接口服务报错的问题
网络协议·http·https