ChronoTomato/internal/websocket/receive.go

56 lines
1.1 KiB
Go
Raw Normal View History

2024-10-22 11:13:41 +00:00
package websocket
import (
"encoding/json"
"time"
2024-10-22 11:13:41 +00:00
"github.com/gorilla/websocket"
GoTomato "git.smsvc.net/pomodoro/GoTomato/pkg/models"
2024-10-22 11:13:41 +00:00
)
var Done = make(chan struct{})
// Receives websocket messages and writes them to a channel.
// Closes the channel if websocket closes.
func (c *Client) ProcessServerMessages(channel chan<- GoTomato.ServerMessage) {
var serverMessage, prevMessage GoTomato.ServerMessage
2024-10-22 11:13:41 +00:00
defer close(Done)
for {
c.Conn.SetReadDeadline(time.Now().Add(10 * time.Second))
_, message, err := c.Conn.ReadMessage()
2024-10-22 11:13:41 +00:00
if err != nil {
// On normal closure exit gracefully
if websocket.IsCloseError(err, websocket.CloseNormalClosure) {
return
}
2024-10-22 11:13:41 +00:00
c.LastErr = err
// Try to reconnect on unexpected disconnect
for {
channel <- prevMessage // send previous ServerMessage to update view
time.Sleep(time.Second)
// reconnect while preserving password
pw := c.Password
*c = Connect(c.Server)
c.Password = pw
if c.Connected() {
break
}
}
2024-10-22 11:13:41 +00:00
continue
}
err = json.Unmarshal(message, &serverMessage)
c.LastErr = err
channel <- serverMessage
prevMessage = serverMessage
2024-10-22 11:13:41 +00:00
}
}