go_pinger.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package pubsub
  2. import (
  3. "fmt"
  4. "time"
  5. "github.com/gorilla/websocket"
  6. )
  7. func go_pinger(c *Connection) {
  8. // Pinger (sender)
  9. go func(c *Connection) {
  10. for {
  11. select {
  12. case <-time.After(1 * time.Second):
  13. if c.active && !c.ping_sended {
  14. if time.Since(c.ping_start) > TwitchApiPingEach {
  15. if err := c.Connection.WriteMessage(
  16. websocket.TextMessage,
  17. Answer{Type: Ping}.JSON(),
  18. ); err != nil {
  19. c.onError(err)
  20. c.active = false
  21. c.onDisconnect()
  22. } else {
  23. c.ping_start = time.Now()
  24. c.ping_sended = true
  25. c.onPing(c.ping_start)
  26. }
  27. }
  28. }
  29. case <-c.done:
  30. return
  31. }
  32. }
  33. }(c)
  34. // Pinger (handler)
  35. go func(c *Connection) {
  36. for {
  37. select {
  38. case <-time.After(1 * time.Second):
  39. if c.active && c.ping_sended {
  40. if time.Since(c.ping_start) > TwitchApiPingTimeout {
  41. c.onInfo(fmt.Sprintf("warning, no %s response more than %d seconds", Pong, TwitchApiPingTimeout))
  42. c.active = false
  43. c.onDisconnect()
  44. c.ping_start = time.Now()
  45. c.ping_sended = false
  46. if err := c.Connection.Close(); err != nil {
  47. c.onError(err)
  48. }
  49. }
  50. }
  51. case <-c.done:
  52. return
  53. }
  54. }
  55. }(c)
  56. }