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>
相关推荐
_waylau3 分钟前
Spring Framework HTTP服务客户端详解
java·后端·网络协议·spring·http·spring cloud
爱刷碗的苏泓舒40 分钟前
网络通信入门之 NTRIP、HTTP、TCP 与 IP 的关系:协议分层、连接过程以及实时数据流
网络协议·tcp/ip·http·网络通信·rtcm·监控运维·ntrip
Lhappy嘻嘻1 小时前
网络(四)|全网最细网络层原理:IP 协议、IP 地址分类、子网划分、路由转发、NAT 穿透详解
java·笔记·网络协议·计算机网络
我星期八休息10 小时前
网络编程—应用层HTTP协议
linux·运维·开发语言·前端·网络·网络协议·http
ShineWinsu11 小时前
对于Linux:UDPsocket编程基础的解析
linux·运维·网络协议·udp·ip·端口号·进程间通信
ITxiaobing202312 小时前
IP库与AppsFlyer数据对账指南:破解国家/地区数据不一致的难题
网络·网络协议
宠友信息18 小时前
MySQL复合索引与Druid优化仿小红书源码个人主页查询链路
数据库·spring boot·websocket·mysql·uni-app
VX_1821 小时前
域名SSL证书监测平台
网络·网络协议·ssl
tiantianuser1 天前
NVME-oF IP 设计7 :设计扫盲5
网络协议·rdma·roce v2·nvme of
ShineWinsu1 天前
对于Linux:TCPsocket编程基础的解析
linux·网络协议·tcp/ip·面试·笔试·进程·远程指令