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>
相关推荐
Li emily13 小时前
成功接入A股实时行情API获取实时市场数据
人工智能·python·金融·fastapi
IT利刃出鞘14 小时前
SSL证书--手动生成自签名IP证书
网络·网络协议·ssl
Trouvaille ~19 小时前
【Linux】TCP协议基础与连接管理详解:从三次握手到四次挥手
linux·运维·服务器·网络·c++·网络协议·tcp/ip
njmanong19 小时前
Google点名处置IPIDEA及子品牌:代理IP行业进入强治理期
网络·网络协议·tcp/ip
郝学胜-神的一滴21 小时前
TCP通讯的艺术:从握手到挥手的优雅对话
开发语言·网络·网络协议·tcp/ip·程序人生
CS创新实验室1 天前
《计算机网络》深入学:TCP协议的设计与演进
网络协议·tcp/ip·计算机网络
运维有小邓@1 天前
基于证书的身份验证:入门指南
网络协议·https·ssl
她说..1 天前
万字详解WebSocket的用法
java·网络·websocket·网络协议·springboot
会周易的程序员1 天前
openplc runtime v4 安全
网络·c++·物联网·websocket·安全·https·ssl
专注VB编程开发20年1 天前
PLC协议:Modbus.Device(NModbus4)和手动 Socket.BeginConnect (APM异步编程模型)对比
网络·网络协议·tcp/ip·plc