2024-10-22 11:13:41 +00:00
|
|
|
package websocket
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
2024-11-06 08:03:25 +00:00
|
|
|
"time"
|
|
|
|
|
2024-10-22 11:13:41 +00:00
|
|
|
"github.com/gorilla/websocket"
|
2024-10-27 20:34:53 +00:00
|
|
|
|
|
|
|
GoTomato "git.smsvc.net/pomodoro/GoTomato/pkg/models"
|
2024-10-22 11:13:41 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
var Done = make(chan struct{})
|
|
|
|
|
2024-10-31 06:37:50 +00:00
|
|
|
// Receives websocket messages and writes them to a channel.
|
|
|
|
// Closes the channel if websocket closes.
|
2024-11-06 08:03:25 +00:00
|
|
|
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 {
|
2024-10-30 08:51:59 +00:00
|
|
|
_, message, err := c.Conn.ReadMessage()
|
2024-10-22 11:13:41 +00:00
|
|
|
if err != nil {
|
2024-11-06 08:03:25 +00:00
|
|
|
// On normal closure exit gracefully
|
2024-10-27 15:46:11 +00:00
|
|
|
if websocket.IsCloseError(err, websocket.CloseNormalClosure) {
|
2024-10-24 05:25:48 +00:00
|
|
|
return
|
|
|
|
}
|
2024-10-22 11:13:41 +00:00
|
|
|
|
2024-11-06 08:03:25 +00:00
|
|
|
// Try to reconnect on unexpected disconnect
|
|
|
|
for {
|
|
|
|
channel <- prevMessage // send previous ServerMessage to update view
|
|
|
|
time.Sleep(time.Second)
|
|
|
|
*c = Connect(c.Server)
|
|
|
|
if c.Connected() {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
2024-10-22 11:13:41 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2024-11-06 08:03:25 +00:00
|
|
|
err = json.Unmarshal(message, &serverMessage)
|
|
|
|
c.LastErr = err
|
|
|
|
|
2024-10-27 09:41:31 +00:00
|
|
|
channel <- serverMessage
|
2024-11-06 08:03:25 +00:00
|
|
|
prevMessage = serverMessage
|
2024-10-22 11:13:41 +00:00
|
|
|
}
|
|
|
|
}
|