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>
相关推荐
猫头虎7 小时前
如何查看局域网内IP冲突问题?如何查看局域网IP环绕问题?arp -a命令如何使用?
网络·python·网络协议·tcp/ip·开源·pandas·pip
爱吃小胖橘10 小时前
Unity网络开发--超文本传输协议Http(1)
开发语言·网络·网络协议·http·c#·游戏引擎
北城以北12314 小时前
生成树协议STP详解
网络协议
杰瑞学AI15 小时前
我的全栈学习之旅:FastAPI (持续更新!!!)
后端·python·websocket·学习·http·restful·fastapi
雪碧聊技术19 小时前
关于springboot定时任务和websocket的思考
websocket·springboot定时任务
ErizJ20 小时前
WebSocket | 一点简单了解
网络·websocket·网络协议
qq_326699111 天前
Python解析Excel数据从入门到精通
websocket
CiLerLinux1 天前
第五十二章 ESP32S3 UDP 实验
网络·单片机·嵌入式硬件·网络协议·udp
切糕师学AI1 天前
P2P技术
网络·网络协议·p2p
Chandler242 天前
一图掌握 网络协议 核心要点
网络协议·tcp/ip·计算机网络·http