From a5028f9c71ebcd1aa0af29b3426e9d13498e6812 Mon Sep 17 00:00:00 2001 From: zhiyu1998 <542716863@qq.com> Date: Fri, 22 Nov 2024 21:03:59 +0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9E=20fix:=20=E4=BF=AE=E5=A4=8D?= =?UTF-8?q?=E7=BD=91=E7=BB=9C=E4=B8=8A=E4=B8=8B=E8=A1=8C=E6=B2=A1=E6=9C=89?= =?UTF-8?q?=E6=AD=A3=E7=A1=AE=E5=A4=84=E7=90=86=E7=B4=AF=E8=AE=A1=E5=80=BC?= =?UTF-8?q?=E7=9A=84=E9=87=8D=E7=BD=AE=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- server/app/r/api/network2/route.js | 28 ++++++++++++++++++++++------ 1 file changed, 22 insertions(+), 6 deletions(-) diff --git a/server/app/r/api/network2/route.js b/server/app/r/api/network2/route.js index a3b5fd3..1b96685 100644 --- a/server/app/r/api/network2/route.js +++ b/server/app/r/api/network2/route.js @@ -5,6 +5,7 @@ import si from 'systeminformation'; let lastBytesReceived = 0; let lastBytesSent = 0; let lastTimestamp = Date.now(); +let isFirstRun = true; async function getLinuxStats() { const data = await fs.readFile('/proc/net/dev', 'utf8'); @@ -58,18 +59,33 @@ async function getNetworkStats() { const now = Date.now(); const timeDiff = (now - lastTimestamp) / 1000; - const downloadSpeed = Math.max(0, (bytesReceived - lastBytesReceived) / timeDiff); - const uploadSpeed = Math.max(0, (bytesSent - lastBytesSent) / timeDiff); + let downloadSpeed = 0; + let uploadSpeed = 0; + if (!isFirstRun) { + // 检查是否发生了计数器重置或异常值 + if (bytesReceived >= lastBytesReceived && bytesSent >= lastBytesSent) { + downloadSpeed = (bytesReceived - lastBytesReceived) / timeDiff; + uploadSpeed = (bytesSent - lastBytesSent) / timeDiff; + + // 设置合理的上限值(比如 1GB/s) + const MAX_SPEED = 1024 * 1024 * 1024; // 1 GB/s + downloadSpeed = Math.min(downloadSpeed, MAX_SPEED); + uploadSpeed = Math.min(uploadSpeed, MAX_SPEED); + } + } + + // 更新状态 lastBytesReceived = bytesReceived; lastBytesSent = bytesSent; lastTimestamp = now; + isFirstRun = false; return { - downloadSpeed: (downloadSpeed / 1024).toFixed(2), - uploadSpeed: (uploadSpeed / 1024).toFixed(2), - totalReceived: (bytesReceived / (1024 * 1024 * 1024)).toFixed(2), - totalSent: (bytesSent / (1024 * 1024 * 1024)).toFixed(2), + downloadSpeed: (downloadSpeed / 1024).toFixed(2), // KB/s + uploadSpeed: (uploadSpeed / 1024).toFixed(2), // KB/s + totalReceived: (bytesReceived / (1024 * 1024 * 1024)).toFixed(2), // GB + totalSent: (bytesSent / (1024 * 1024 * 1024)).toFixed(2), // GB timestamp: now }; } catch (error) {