本文主要是介绍vue2使用websocket和echars动态展示本机CPU使用情况,后端框架使用fastapi,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
后端代码:
from fastapi import FastAPI, WebSocket
import psutil
import asyncioapp = 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
<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>
这篇关于vue2使用websocket和echars动态展示本机CPU使用情况,后端框架使用fastapi的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!