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>
相关推荐
IP老炮不瞎唠1 小时前
批量任务vs持续监控:不同市场调研场景下的配置策略
大数据·网络·网络协议
KaMeidebaby2 小时前
卡梅德生物技术快报|组蛋白乙酰化修饰调控动脉粥样硬化的分子机制及中药表观干预研究
网络·人工智能·网络协议·tcp/ip·算法
夜月yeyue2 小时前
TCP/IP 协议解析
linux·服务器·c语言·网络·网络协议·tcp/ip
network_tester2 小时前
TSN台架系统测试:从实验室验证到智能驾驶落地的关键桥梁
网络·网络协议·5g·汽车·信息与通信·信号处理·tcpdump
Wonderful U2 小时前
基于 Django Channels 与 WebSocket 的实时聊天室:群聊、私聊、离线消息与持久化存储全实现
python·websocket·django
xlq223223 小时前
63.tcp可靠性
网络·网络协议·tcp/ip
TechWayfarer3 小时前
IP精准定位服务接入实战:广告投放如何用位置数据做定向策略
python·网络协议·tcp/ip·flask
shuxiaohua3 小时前
一次现网问题定位-websocket断连问题
网络·websocket·网络协议
越甲八千3 小时前
本地验证http服务器拉取文件
服务器·网络协议·http
上海云盾-小余13 小时前
BGP 高防 IP 与 CDN 混合部署:攻防场景选型实战指南
网络·网络协议·tcp/ip