From 1e787cb60723e9fe848aa6d89d5e5f1350de4fef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=96=E7=95=8C?= Date: Tue, 3 Dec 2024 21:43:11 +0800 Subject: [PATCH] Fix initial traffic value --- experimental/clashapi/server.go | 16 +++++++--------- experimental/libbox/command_status.go | 22 ++++++++++------------ 2 files changed, 17 insertions(+), 21 deletions(-) diff --git a/experimental/clashapi/server.go b/experimental/clashapi/server.go index f47e08cf..909583b3 100644 --- a/experimental/clashapi/server.go +++ b/experimental/clashapi/server.go @@ -316,18 +316,15 @@ func traffic(trafficManager *trafficontrol.Manager) func(w http.ResponseWriter, tick := time.NewTicker(time.Second) defer tick.Stop() buf := &bytes.Buffer{} - var ( - uploadTotal int64 - doanloadTotal int64 - err error - ) + uploadTotal, downloadTotal := trafficManager.Total() for range tick.C { buf.Reset() uploadTotalNew, downloadTotalNew := trafficManager.Total() - if err := json.NewEncoder(buf).Encode(Traffic{ + err := json.NewEncoder(buf).Encode(Traffic{ Up: uploadTotalNew - uploadTotal, - Down: downloadTotalNew - doanloadTotal, - }); err != nil { + Down: downloadTotalNew - downloadTotal, + }) + if err != nil { break } if conn == nil { @@ -339,8 +336,9 @@ func traffic(trafficManager *trafficontrol.Manager) func(w http.ResponseWriter, if err != nil { break } + uploadTotal = uploadTotalNew - doanloadTotal = downloadTotalNew + downloadTotal = downloadTotalNew } } } diff --git a/experimental/libbox/command_status.go b/experimental/libbox/command_status.go index 07e66934..a6280d0f 100644 --- a/experimental/libbox/command_status.go +++ b/experimental/libbox/command_status.go @@ -51,19 +51,10 @@ func (s *CommandServer) handleStatusConn(conn net.Conn) error { ticker := time.NewTicker(time.Duration(interval)) defer ticker.Stop() ctx := connKeepAlive(conn) - var ( - status StatusMessage - uploadTotal int64 - downloadTotal int64 - ) + status := s.readStatus() + uploadTotal := status.UplinkTotal + downloadTotal := status.DownlinkTotal for { - status = s.readStatus() - upload := status.UplinkTotal - uploadTotal - download := status.DownlinkTotal - downloadTotal - uploadTotal = status.UplinkTotal - downloadTotal = status.DownlinkTotal - status.Uplink = upload - status.Downlink = download err = binary.Write(conn, binary.BigEndian, status) if err != nil { return err @@ -73,6 +64,13 @@ func (s *CommandServer) handleStatusConn(conn net.Conn) error { return ctx.Err() case <-ticker.C: } + status = s.readStatus() + upload := status.UplinkTotal - uploadTotal + download := status.DownlinkTotal - downloadTotal + uploadTotal = status.UplinkTotal + downloadTotal = status.DownlinkTotal + status.Uplink = upload + status.Downlink = download } }