Skip to content

Commit

Permalink
feat(serve): Limit the speed of the messages sent by the server
Browse files Browse the repository at this point in the history
  • Loading branch information
etu committed Jun 23, 2024
1 parent f72eaad commit 0d3745f
Showing 1 changed file with 13 additions and 0 deletions.
13 changes: 13 additions & 0 deletions serve.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"net/http"
"os"
"sync"
"time"

"github.com/gorilla/mux"
"github.com/gorilla/websocket"
Expand Down Expand Up @@ -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()
Expand Down

0 comments on commit 0d3745f

Please sign in to comment.