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:
parent
1d38db97a5
commit
e8656e8b6e
2 changed files with 9 additions and 13 deletions
|
@ -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"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
|
@ -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
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
Loading…
Reference in a new issue