go_reconnector.go 914 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. package pubsub
  2. import (
  3. "fmt"
  4. "time"
  5. "github.com/gorilla/websocket"
  6. )
  7. func go_reconnector(c *Connection) {
  8. go func(c *Connection) {
  9. for {
  10. select {
  11. case <-c.done:
  12. return
  13. default:
  14. if !c.active && len(c.topics) > 0 {
  15. c.onInfo(fmt.Sprintf("reconnecting to: %s", c.url.String()))
  16. conn, _, err := websocket.DefaultDialer.Dial(c.url.String(), nil)
  17. if err != nil {
  18. c.onError(err)
  19. // Wait 1 second or return immediately
  20. select {
  21. case <-time.After(time.Second):
  22. case <-c.done:
  23. return
  24. }
  25. } else {
  26. c.onInfo("reconnected successfully")
  27. c.Connection = conn
  28. c.active = true
  29. c.onConnect()
  30. // Listen all topics
  31. c.listenTopis()
  32. }
  33. } else {
  34. // Wait 1 second or return immediately
  35. select {
  36. case <-time.After(time.Second):
  37. case <-c.done:
  38. return
  39. }
  40. }
  41. }
  42. }
  43. }(c)
  44. }