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>
相关推荐
2502_911679141 分钟前
KEYSIGHT N5172B EXG 微波模拟信号发生器:经济高效的射频测试解决方案
科技·网络协议·信息与通信·信号处理
开开心心_Every13 分钟前
网络管理员IP配置工具:设置多台电脑地址
运维·服务器·网络·网络协议·学习·tcp/ip·edge
北京耐用通信29 分钟前
耐达讯自动化Profibus总线光纤中继器在连接测距仪中的应用
人工智能·物联网·网络协议·网络安全·自动化·信息与通信
全栈软件开发1 小时前
PHP实时消息聊天室源码 PHP+WebSocket
开发语言·websocket·php
yi碗汤园1 小时前
【超详细】TCP编程与UDP编程
网络·网络协议·tcp/ip·unity·udp·visual studio
Ankie Wan1 小时前
SOME/IP: Scalable service-Oriented MiddlewarE over IP车载以太网的服务化通信协议
网络协议·tcp/ip·ecu·can总线·some/ip·autostar
海棠蚀omo1 小时前
从初识到深入:一次完整的 HTTP 协议系统性理解之旅
网络·网络协议·http
北京盟通科技官方账号2 小时前
Docker 容器化部署 EtherNet/IP 协议栈(ESDK):Windows 与国产银河麒麟 V10 实测对比
网络·网络协议·tcp/ip·docker·国产系统·ethernet/ip·工业协议
举手2 小时前
UDP Echo Server(学习版)
linux·服务器·网络·网络协议·学习·udp