vue2使用websocket和echars动态展示本机CPU使用情况,后端框架使用fastapi

后端代码:

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

<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>

  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值