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
|
|
|
)
|
|
|
|
|
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) {
|
2024-11-18 18:53:21 +00:00
|
|
|
var serverMessage GoTomato.ServerMessage
|
2024-10-22 11:13:41 +00:00
|
|
|
|
|
|
|
defer close(Done)
|
|
|
|
|
|
|
|
for {
|
2024-11-13 16:16:50 +00:00
|
|
|
c.Conn.SetReadDeadline(time.Now().Add(10 * time.Second))
|
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-20 08:32:04 +00:00
|
|
|
c.LastErr = err
|
|
|
|
|
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-20 08:32:04 +00:00
|
|
|
// reset connection and reconnect
|
|
|
|
c.Conn = nil
|
|
|
|
pw := c.Password
|
|
|
|
for !c.Connected() {
|
2024-11-18 18:53:21 +00:00
|
|
|
channel <- serverMessage // send last known ServerMessage to update view
|
2024-11-06 08:03:25 +00:00
|
|
|
time.Sleep(time.Second)
|
|
|
|
*c = Connect(c.Server)
|
|
|
|
}
|
2024-11-20 08:32:04 +00:00
|
|
|
c.Password = pw
|
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-10-22 11:13:41 +00:00
|
|
|
}
|
|
|
|
}
|