Skip to content

Commit

Permalink
fix: broadcast stats more effectively
Browse files Browse the repository at this point in the history
  • Loading branch information
ivynya committed Dec 26, 2023
1 parent e56d2d2 commit f20b730
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 15 deletions.
29 changes: 19 additions & 10 deletions server/broadcast.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,25 +48,34 @@ func broadcastToClient(c map[string]*websocket.Conn, req *internal.Request) erro
return nil
}

func broadcastAll(c map[string]*websocket.Conn, req *internal.Request) error {
// broadcast to all connections and return false if >= 1 failure
func broadcastAll(c map[string]*websocket.Conn, req *internal.Request) bool {
data, _ := json.Marshal(req)

ok := true
for tag, conn := range c {
err := conn.WriteMessage(websocket.TextMessage, data)
if err != nil {
delete(c, tag)
return err
ok = false
}
}
return nil
return ok
}

func updateConnCount(clientType string, c *map[string]*websocket.Conn) {
err := broadcastAll(*c, &internal.Request{
Action: clientType,
Data: strconv.Itoa(len(*c)),
})
if err != nil {
updateConnCount(clientType, c)
// broadcast number of clients and providers to all clients
func broadcastConnectionStats(clients map[string]*websocket.Conn, providers map[string]*websocket.Conn) {
retry_remaining := 3
ok := true
for ok != true && retry_remaining > 0 {
ok = ok && broadcastAll(clients, &internal.Request{
Action: "clients",
Data: strconv.Itoa(len(clients)),
})
ok = ok && broadcastAll(clients, &internal.Request{
Action: "providers",
Data: strconv.Itoa(len(providers)),
})
retry_remaining--
}
}
10 changes: 5 additions & 5 deletions server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ func main() {
// Log join message
fmt.Println("Provider joined from " + c.RemoteAddr().String())
fmt.Println("Total providers:", len(providers))
updateConnCount("providers", &providers)
broadcastConnectionStats(clients, providers)

for {
// Read message from provider
Expand Down Expand Up @@ -69,7 +69,7 @@ func main() {

// Unregister provider
delete(providers, tag)
updateConnCount("providers", &providers)
broadcastConnectionStats(clients, providers)
}))

// WebSocket endpoint
Expand All @@ -81,10 +81,10 @@ func main() {
}
clients[tag] = c

// Log join message
// Log join message and broadcast counts
fmt.Println("Client joined from " + c.RemoteAddr().String())
fmt.Println("Total clients:", len(clients))
updateConnCount("clients", &clients)
broadcastConnectionStats(clients, providers)

for {
// Read message from client
Expand Down Expand Up @@ -118,7 +118,7 @@ func main() {

// Unregister client
delete(clients, tag)
updateConnCount("clients", &clients)
broadcastConnectionStats(clients, providers)
}))

// Start the server
Expand Down

0 comments on commit f20b730

Please sign in to comment.