client_ws.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. package cpn
  2. import (
  3. "git.wanbits.io/joe/nnet"
  4. "github.com/gorilla/websocket"
  5. "net"
  6. "time"
  7. )
  8. const (
  9. WS = 1
  10. TCP = 2
  11. )
  12. type ClientOption func(*Client)
  13. type connector func(string, uint64) error
  14. func WithReconn(interval time.Duration) ClientOption {
  15. return func(c *Client) {
  16. c.reconnInterval = interval
  17. }
  18. }
  19. type Client struct {
  20. *Hub
  21. addr string
  22. id uint64
  23. ctr connector
  24. reconnInterval time.Duration
  25. }
  26. func NewClient(protocol int, cf *nnet.HubConfig, cb nnet.ISessionCallback, p nnet.IProtocol, opts ...ClientOption) nnet.IHub {
  27. c := &Client{
  28. Hub: newHub(cf, cb, p),
  29. reconnInterval: 0,
  30. }
  31. for _, opt := range opts {
  32. opt(c)
  33. }
  34. c.ctr = c.connectTcp
  35. if protocol == WS {
  36. c.ctr = c.connectWs
  37. }
  38. return c
  39. }
  40. func NewWsClient(cf *nnet.HubConfig, cb nnet.ISessionCallback, p nnet.IProtocol, opts ...ClientOption) nnet.IHub {
  41. return NewClient(WS, cf, cb, p, opts...)
  42. }
  43. func (self *Client) NewConnection(addr string, id uint64) error {
  44. self.addr, self.id = addr, id
  45. if self.reconnInterval == 0 {
  46. return self.ctr(addr, id)
  47. }
  48. self.StartReconn()
  49. return nil
  50. }
  51. func (self *Client) StartReconn() {
  52. go func() {
  53. var err error
  54. for {
  55. err = self.ctr(self.addr, self.id)
  56. if err == nil {
  57. return
  58. }
  59. time.Sleep(self.reconnInterval)
  60. }
  61. }()
  62. }
  63. func (self *Client) connectWs(addr string, id uint64) error {
  64. conn, _, err := websocket.DefaultDialer.Dial(addr, nil)
  65. if err != nil {
  66. return err
  67. }
  68. self.wg.Add(1)
  69. go func() {
  70. ses := newSession(NewWsConn(conn), self)
  71. ses.UpdateId(id)
  72. ses.Do()
  73. self.wg.Done()
  74. }()
  75. return nil
  76. }
  77. func (self *Client) connectTcp(addr string, id uint64) error {
  78. tcpAddr, err := net.ResolveTCPAddr("tcp", addr)
  79. if err != nil {
  80. return err
  81. }
  82. conn, err := net.DialTCP("tcp", nil, tcpAddr)
  83. if err != nil {
  84. return err
  85. }
  86. self.wg.Add(1)
  87. go func() {
  88. ses := newSession(TcpConn{conn}, self)
  89. ses.UpdateId(id)
  90. ses.Do()
  91. self.wg.Done()
  92. }()
  93. return nil
  94. }