Compare commits
3 commits
f4b1e7c808
...
a0463ad817
Author | SHA1 | Date | |
---|---|---|---|
a0463ad817 | |||
0ab0884508 | |||
bf9b818940 |
6 changed files with 28 additions and 8 deletions
|
@ -54,6 +54,7 @@ func Start() {
|
|||
r := http.NewServeMux()
|
||||
r.HandleFunc("/", websocket.HandleConnection)
|
||||
go websocket.SendPermanentBroadCastMessage()
|
||||
go websocket.RemoveStaleClients()
|
||||
|
||||
helper.Logger.Info("GoTomato started", "version", metadata.GoTomatoVersion)
|
||||
helper.Logger.Info("Websocket listening", "address", listen)
|
||||
|
|
|
@ -21,18 +21,15 @@ func SendPermanentBroadCastMessage() {
|
|||
}
|
||||
|
||||
// Iterate over all connected clients and broadcast the message
|
||||
mu.Lock()
|
||||
for _, client := range Clients {
|
||||
// Remove unresponsive client
|
||||
if client.IsStale() {
|
||||
client.Conn.Close()
|
||||
continue
|
||||
}
|
||||
// Send message to client
|
||||
err := client.SendMessage(websocket.TextMessage, jsonMessage)
|
||||
if err != nil {
|
||||
helper.Logger.Info("Error broadcasting to client:", "msg", err, "host", client.RealIP, "clients", len(Clients))
|
||||
}
|
||||
}
|
||||
mu.Unlock()
|
||||
|
||||
<-tick.C
|
||||
}
|
||||
|
|
|
@ -22,7 +22,9 @@ func handleClientCommands(c models.WebsocketClient) {
|
|||
_, message, err := ws.ReadMessage()
|
||||
if err != nil {
|
||||
// remove client on error/disconnect
|
||||
mu.Lock()
|
||||
delete(Clients, ws.LocalAddr())
|
||||
mu.Unlock()
|
||||
helper.Logger.Info("Client disconnected:", "msg", err, "host", c.RealIP, "clients", len(Clients))
|
||||
break
|
||||
}
|
||||
|
|
|
@ -36,8 +36,7 @@ func HandleConnection(w http.ResponseWriter, r *http.Request) {
|
|||
LastPong: time.Now(),
|
||||
RealIP: r.RemoteAddr,
|
||||
}
|
||||
|
||||
client.Conn.SetPongHandler(func(appData string) error {
|
||||
client.Conn.SetPongHandler(func(s string) error {
|
||||
client.LastPong = time.Now()
|
||||
return nil
|
||||
})
|
||||
|
|
21
internal/websocket/staleClients.go
Normal file
21
internal/websocket/staleClients.go
Normal file
|
@ -0,0 +1,21 @@
|
|||
package websocket
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// Check and remove stale clients
|
||||
func RemoveStaleClients() {
|
||||
ticker := time.NewTicker(30 * time.Second)
|
||||
defer ticker.Stop()
|
||||
|
||||
for range ticker.C {
|
||||
mu.Lock()
|
||||
for _, client := range Clients {
|
||||
if client.IsStale() {
|
||||
client.Conn.Close()
|
||||
}
|
||||
}
|
||||
mu.Unlock()
|
||||
}
|
||||
}
|
|
@ -39,7 +39,7 @@ func (c *WebsocketClient) SendMessage(messageType int, data []byte) error {
|
|||
return nil
|
||||
}
|
||||
|
||||
// Check if websockets last Pong is recent
|
||||
// Checks if the websockets last Pong is recent
|
||||
func (c *WebsocketClient) IsStale() bool {
|
||||
return time.Since(c.LastPong) > (TIMEOUT * time.Second)
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue