From 0d3745f6a586e1a31a0bbc625d95f949fbde2572 Mon Sep 17 00:00:00 2001 From: Elis Hirwing Date: Sun, 23 Jun 2024 16:16:33 +0200 Subject: [PATCH] feat(serve): Limit the speed of the messages sent by the server --- serve.go | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/serve.go b/serve.go index be34310..e82ddaa 100644 --- a/serve.go +++ b/serve.go @@ -9,6 +9,7 @@ import ( "net/http" "os" "sync" + "time" "github.com/gorilla/mux" "github.com/gorilla/websocket" @@ -273,9 +274,21 @@ func (serve *Serve) newRouter() *mux.Router { } }() + // Store last send time to avoid sending too many messages per second + var lastSend int64 + for { select { case <-serve.stateChange: + // Limit the amount of messages sent per second to send at most every 100ms + // to avoid flooding the client with messages. + if ((time.Now().UnixNano() / int64(time.Millisecond)) - 100) < lastSend { + continue + } + + // Store the last send time + lastSend = time.Now().UnixNano() / int64(time.Millisecond) + for client, name := range serve.clientSubscriptions { // Send the list state regardless of subscription listState := serve.GetServerList()