fix: prevent concurrent write to websocket connection
- refactor client handling and message broadcasting
- replace Client struct
- implement SendMessage method in Client struct for safer message sending
- update client map to use *models.Client instead of bool
- adjust BroadcastMessage and RunPomodoroTimer functions to use new client type
🤖
This commit is contained in:
parent
ffc6913344
commit
4471c86a0c
7 changed files with 53 additions and 17 deletions
|
@ -8,7 +8,7 @@ import (
|
|||
)
|
||||
|
||||
// BroadcastMessage sends a message to all connected WebSocket clients.
|
||||
func BroadcastMessage(clients map[*websocket.Conn]bool, message models.BroadcastMessage) {
|
||||
func BroadcastMessage(clients map[*websocket.Conn]*models.Client, message models.BroadcastMessage) {
|
||||
// Marshal the message into JSON format
|
||||
jsonMessage, err := json.Marshal(message)
|
||||
if err != nil {
|
||||
|
@ -17,12 +17,11 @@ func BroadcastMessage(clients map[*websocket.Conn]bool, message models.Broadcast
|
|||
}
|
||||
|
||||
// Iterate over all connected clients and broadcast the message
|
||||
for client := range clients {
|
||||
err := client.WriteMessage(websocket.TextMessage, jsonMessage)
|
||||
for _, client := range clients {
|
||||
err := client.SendMessage(websocket.TextMessage, jsonMessage)
|
||||
if err != nil {
|
||||
log.Printf("Error broadcasting to client: %v", err)
|
||||
client.Close()
|
||||
delete(clients, client) // Remove the client if an error occurs
|
||||
// The client is responsible for closing itself on error
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue