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>
相关推荐
佳児素花痴╮38 分钟前
服务器模型、网络调试工具、网络协议头分析
服务器·网络·网络协议
阿pin1 小时前
TCP VS UDP
网络协议·tcp/ip·udp
丑过三八线2 小时前
002 - 【FastAPI 入门教程】请求体与数据校验
fastapi
SendTomo6 小时前
SendTomo稳定传输三大核心策略
javascript·网络协议·webrtc·html5·p2p
丑过三八线6 小时前
001 -【FastAPI 入门教程】 FastAPI Helloword
前端·chrome·fastapi
CANWeb冗余现场总线6 小时前
2毫秒扫描周期以太网Modbus TCP UDP高速通信:西门子SMART PLC+CANWeb现场总线远程扩展IO模块
网络协议·tcp/ip·udp
阿pin6 小时前
HTTP 与 HTTPS 详解
网络协议·http·https
SamChan907 小时前
FastAPI+Celery+Redis搭建企业级PDF翻译异步任务系统
redis·后端·python·pdf·wpf·fastapi
阿pin7 小时前
HTTP 协议的演进
网络·网络协议·http
跨境技工小黎7 小时前
IPFoxy动态住宅IP实测:做数据采集和爬虫可行吗?
爬虫·网络协议·tcp/ip