refactor: update reconnect code for better understanding

This commit is contained in:
Sebastian Mark 2024-11-20 09:32:04 +01:00
parent 1d38db97a5
commit 2266b94b7c
2 changed files with 9 additions and 13 deletions

View file

@ -1,9 +1,10 @@
package websocket package websocket
import ( import (
"github.com/gorilla/websocket"
"time" "time"
"github.com/gorilla/websocket"
ChronoTomato "git.smsvc.net/pomodoro/ChronoTomato/pkg/models" ChronoTomato "git.smsvc.net/pomodoro/ChronoTomato/pkg/models"
) )

View file

@ -22,27 +22,22 @@ func (c *Client) ProcessServerMessages(channel chan<- GoTomato.ServerMessage) {
c.Conn.SetReadDeadline(time.Now().Add(10 * time.Second)) c.Conn.SetReadDeadline(time.Now().Add(10 * time.Second))
_, message, err := c.Conn.ReadMessage() _, message, err := c.Conn.ReadMessage()
if err != nil { if err != nil {
c.LastErr = err
// On normal closure exit gracefully // On normal closure exit gracefully
if websocket.IsCloseError(err, websocket.CloseNormalClosure) { if websocket.IsCloseError(err, websocket.CloseNormalClosure) {
return return
} }
c.LastErr = err // reset connection and reconnect
// Try to reconnect on unexpected disconnect c.Conn = nil
for { pw := c.Password
for !c.Connected() {
channel <- serverMessage // send last known ServerMessage to update view channel <- serverMessage // send last known ServerMessage to update view
time.Sleep(time.Second) time.Sleep(time.Second)
// reconnect while preserving password
pw := c.Password
*c = Connect(c.Server) *c = Connect(c.Server)
c.Password = pw
if c.Connected() {
break
}
} }
c.Password = pw
continue continue
} }