go_reconnector.go 974 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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.ping_start = time.Now()
  28. c.ping_sended = false
  29. c.Connection = conn
  30. c.active = true
  31. c.onConnect()
  32. // Listen all topics
  33. c.listenTopis()
  34. }
  35. } else {
  36. // Wait 1 second or return immediately
  37. select {
  38. case <-time.After(time.Second):
  39. case <-c.done:
  40. return
  41. }
  42. }
  43. }
  44. }
  45. }(c)
  46. }