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>
相关推荐
jfqqqqq8 小时前
使用pem和key文件给springboot开启https服务
网络协议·http·https
Cherry Zack10 小时前
FastAPI 入门指南 :基础概念与核心特性
开发语言·python·fastapi·1024程序员节
LCMICRO-1331084774613 小时前
长芯微LDUM3160完全P2P替代ADUM3160,LDUM3160是一款采用ADI公司iCoupler® 技术的USB端口隔离器
网络·stm32·单片机·嵌入式硬件·网络协议·fpga开发·硬件工程
Fms_Sa17 小时前
UDP实现客服与客户的咨询对话
网络·网络协议·udp
BIBI204918 小时前
HTTP 请求方法指南:GET, POST, PUT, PATCH, DELETE 区别
网络·网络协议·http
代码不停18 小时前
网络 UDP 和 TCP / IP详细介绍
网络·网络协议·tcp/ip·udp·1024程序员节
深兰科技19 小时前
深兰科技法务大模型亮相,推动律所文书处理智能化
人工智能·scrapy·beautifulsoup·scikit-learn·pyqt·fastapi·深兰科技
☆璇21 小时前
【Linux】应用层协议HTTP
网络·网络协议·http·1024程序员节
小范同学_1 天前
Spring集成WebSocket
java·spring boot·websocket·spring·1024程序员节
子燕若水1 天前
TLS/SSL加密通信过程全解
网络·网络协议·ssl