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 分钟前
Http GET / 请求返回值不同的问题
网络·网络协议·http
liulilittle15 分钟前
eBPF tc prog
服务器·网络·c++·网络协议·tcp/ip·性能·perf
Yana.nice1 小时前
tcp与udp的区别
网络协议·tcp/ip·udp
ayaya_mana2 小时前
NPS 内网穿透,二次开源版新增多种连接协议(含 P2P 配置)
linux·运维·服务器·网络协议·内网穿透·p2p·nps
社恐的下水道蟑螂2 小时前
WebSocket 从入门到生产落地:原理拆解 + 聊天室全实战,搞定前端实时通信
前端·javascript·websocket
Qinana2 小时前
面试官想听什么?WebSocket协议升级、Koa实战与心跳机制全解析
后端·websocket·node.js
博语小屋2 小时前
Reactor、epoll下设计一个简单的网络版本计算器
服务器·开发语言·网络·网络协议·http·php
611#3 小时前
2026 年海外代理 IP 服务商评测:住宅代理、纯净度、稳定性与可用性横向对比
大数据·网络协议·tcp/ip
蜡台3 小时前
SSE WebSocket Socket.IO 三者使用及区别
websocket·网络协议·uniapp·sse·socket.io·eventsource
C++ 老炮儿的技术栈3 小时前
Tcp客户端报错原因分析
linux·c语言·网络·c++·网络协议·tcp/ip