disconnected loop while waiting for redial only after first retry
franck34 opened this issue · comments
Code (from example, but use ws rather than wss)
The server is a raw ws nodejs app, working perfectly with a golang client using gorilla websocket.
package main
import (
"context"
"log"
"time"
"github.com/recws-org/recws"
)
func main() {
ctx, cancel := context.WithCancel(context.Background())
ws := recws.RecConn{
KeepAliveTimeout: 10 * time.Second,
}
ws.Dial("ws://192.168.56.101", nil)
go func() {
time.Sleep(2 * time.Second)
cancel()
}()
for {
select {
case <-ctx.Done():
go ws.Close()
log.Printf("Websocket closed %s", ws.GetURL())
return
default:
if !ws.IsConnected() {
log.Printf("Websocket disconnected %s", ws.GetURL())
continue
}
if err := ws.WriteMessage(1, []byte("Incoming")); err != nil {
log.Printf("Error: WriteMessage %s", ws.GetURL())
return
}
_, message, err := ws.ReadMessage()
if err != nil {
log.Printf("Error: ReadMessage %s", ws.GetURL())
return
}
log.Printf("Success: %s", message)
}
}
}
14:25:30 => 14:25:32 = OK, waiting
14:25:32 => 14:25:34 = disconnected loop ?
14:25:34 = closing
2021/03/17 14:25:30 websocket: bad handshake
2021/03/17 14:25:30 Dial: will try again in 2s seconds.
2021/03/17 14:25:32 Websocket disconnected ws://192.168.56.101
2021/03/17 14:25:32 Websocket disconnected ws://192.168.56.101
2021/03/17 14:25:32 Websocket disconnected ws://192.168.56.101
.....
2021/03/17 14:25:34 Websocket disconnected ws://192.168.56.101
2021/03/17 14:25:34 Websocket disconnected ws://192.168.56.101
2021/03/17 14:25:34 Websocket disconnected ws://192.168.56.101
2021/03/17 14:25:34 Websocket disconnected ws://192.168.56.101
2021/03/17 14:25:34 Websocket disconnected ws://192.168.56.101
2021/03/17 14:25:34 Websocket disconnected ws://192.168.56.101
2021/03/17 14:25:34 Websocket closed ws://192.168.56.101
Note: my ws server was running on port X, but my recws client was pointing to port Y
_, message, err := ws.ReadMessage()
if err != nil {
log.Printf("Error: ReadMessage %s", ws.GetURL())
return
}
must be like this
_, message, err := ws.ReadMessage()
if err != nil {
if !errors.Is(err, recws.ErrNotConnected) {
log.Printf("Error: ReadMessage %s", ws.GetURL())
time.Sleep(time.Second * 5) // for throttle if error repeats
} else {
time.Sleep(time.Millisecond * 100) // for release cpu while wait reconnect
}
continue // go to next read
}
@nikepan please keep in mind that sleeping for a certain amount of time will never be a reliable solution
This sleep not for pause. Only for release cpu and throttle messages. But I will try make it without sleep. Thanks