fix: improve connection check and reconnect

- enhance `Connected()` method
  - send ping message to verify connection status
- refactor reconnect code for better understanding
This commit is contained in:
Sebastian Mark 2024-11-20 09:32:04 +01:00
parent 1d38db97a5
commit 5d24a651c2
2 changed files with 28 additions and 15 deletions

View file

@ -1,9 +1,10 @@
package websocket
import (
"github.com/gorilla/websocket"
"time"
"github.com/gorilla/websocket"
ChronoTomato "git.smsvc.net/pomodoro/ChronoTomato/pkg/models"
)
@ -17,7 +18,23 @@ func Connect(url string) Client {
}
func (c Client) Connected() bool {
return c.Conn != nil
if c.Conn == nil {
return false
}
// Set a pong handler to signal when a pong is received
c.Conn.SetPongHandler(func(s string) error {
c.Conn.SetReadDeadline(time.Now().Add(10 * time.Second))
return nil
})
// Send a ping
err := c.Conn.WriteMessage(websocket.PingMessage, nil)
if err != nil {
return false
}
return true
}
// Disconnects from websocket

View file

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