Skip to content

Commit

Permalink
ws improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
CalebRose committed Oct 28, 2024
1 parent 1901f21 commit ba2f175
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 6 deletions.
5 changes: 4 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,10 @@ func monitorDBForUpdates() {
currentTS := controller.GetUpdatedTimestamp()
if currentTS.UpdatedAt.After(ts.UpdatedAt) {
ts = currentTS
ws.BroadcastTSUpdate(ts)
err := ws.BroadcastTSUpdate(ts)
if err != nil {
log.Printf("Error broadcasting timestamp: %v", err)
}
}

time.Sleep(60 * time.Second)
Expand Down
5 changes: 4 additions & 1 deletion ws/broadcast.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ import (
)

// BroadcastTSUpdate sends the updated timestamp to all connected WebSocket clients
func BroadcastTSUpdate(ts structs.Timestamp) {
func BroadcastTSUpdate(ts structs.Timestamp) error {
mu.Lock()
defer mu.Unlock()
for conn := range clients {
err := conn.WriteJSON(ts)
if err != nil {
Expand All @@ -16,4 +18,5 @@ func BroadcastTSUpdate(ts structs.Timestamp) {
delete(clients, conn) // Remove client on error
}
}
return nil
}
20 changes: 16 additions & 4 deletions ws/websocket.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package ws
import (
"log"
"net/http"
"sync"

"github.com/CalebRose/SimFBA/managers"
"github.com/gorilla/websocket"
Expand All @@ -19,7 +20,10 @@ var upgrader = websocket.Upgrader{
}

// Global map to keep track of connected WebSocket clients
var clients = make(map[*websocket.Conn]bool)
var (
clients = make(map[*websocket.Conn]bool)
mu sync.Mutex
)

// WebSocketHandler handles WebSocket connection requests
func WebSocketHandler(w http.ResponseWriter, r *http.Request) {
Expand All @@ -32,9 +36,19 @@ func WebSocketHandler(w http.ResponseWriter, r *http.Request) {
defer conn.Close()

// Add new WebSocket connection to the clients map
mu.Lock()
clients[conn] = true
mu.Unlock()
log.Println("New WebSocket client connected")

defer func() {
conn.Close()
mu.Lock()
delete(clients, conn)
mu.Unlock()
log.Println("WebSocket client disconnected")
}()

ts := managers.GetTimestamp()
// Send the latest timestamp to the user immediately upon connection
err = conn.WriteJSON(ts)
Expand All @@ -47,9 +61,7 @@ func WebSocketHandler(w http.ResponseWriter, r *http.Request) {
for {
_, msg, err := conn.ReadMessage()
if err != nil {
log.Println("WebSocket client disconnected:", err)
conn.Close()
delete(clients, conn)
log.Println("WebSocket client error:", err)
break
}

Expand Down

0 comments on commit ba2f175

Please sign in to comment.