client.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. package client
  2. import (
  3. "errors"
  4. "fmt"
  5. "git.bvbej.com/bvbej/base-golang/pkg/websocket/client/service"
  6. "git.bvbej.com/bvbej/base-golang/pkg/websocket/codec"
  7. _ "git.bvbej.com/bvbej/base-golang/pkg/websocket/codec/json"
  8. _ "git.bvbej.com/bvbej/base-golang/pkg/websocket/codec/protobuf"
  9. "git.bvbej.com/bvbej/base-golang/tool/assist"
  10. "github.com/gorilla/websocket"
  11. "go.uber.org/zap"
  12. "net/http"
  13. "net/url"
  14. "reflect"
  15. "sync/atomic"
  16. "time"
  17. )
  18. const (
  19. writeWait = 20 * time.Second
  20. pongWait = 60 * time.Second
  21. reconnectWait = 3 * time.Second
  22. pingPeriod = (pongWait * 9) / 10
  23. maxFrameMessageLen = 16 * 1024
  24. maxSendBuffer = 32
  25. )
  26. var (
  27. _ Client = (*client)(nil)
  28. ErrBrokenPipe = errors.New("send to broken pipe")
  29. ErrBufferPoolExceed = errors.New("send buffer exceed")
  30. )
  31. type Client interface {
  32. readLoop()
  33. writeLoop()
  34. ping()
  35. onReceive(msg []byte) error
  36. onSend(msg []byte) error
  37. connect() error
  38. Send(router string, data any) error
  39. Connect(requestHeader http.Header) error
  40. OnReceiveError() <-chan error
  41. }
  42. type client struct {
  43. url url.URL
  44. requestHeader http.Header
  45. logger *zap.Logger
  46. session *service.Session
  47. isConnected *atomic.Bool
  48. routerCodec codec.Codec
  49. send chan []byte
  50. handlers map[string]*service.Handler // 注册的方法列表
  51. onReceiveChan chan error
  52. pingTicker *time.Ticker
  53. }
  54. func New(logger *zap.Logger, url url.URL, decoder string, handlers interface{}) (Client, error) {
  55. if !assist.InArray(url.Scheme, []string{"ws", "wss"}) {
  56. return nil, errors.New(`param: scheme not supported`)
  57. }
  58. routerCodec := codec.GetCodec(decoder)
  59. if routerCodec == nil {
  60. return nil, errors.New(`param: codec not supported`)
  61. }
  62. components := service.RegisterHandler(handlers)
  63. if len(components) == 0 {
  64. return nil, errors.New(`param: handlers unqualified`)
  65. }
  66. c := &client{
  67. logger: logger,
  68. isConnected: new(atomic.Bool),
  69. routerCodec: routerCodec,
  70. url: url,
  71. send: make(chan []byte, maxSendBuffer),
  72. handlers: components,
  73. onReceiveChan: make(chan error, maxSendBuffer),
  74. pingTicker: time.NewTicker(pingPeriod),
  75. }
  76. return c, nil
  77. }
  78. func (c *client) readLoop() {
  79. _ = c.session.Conn.SetReadDeadline(time.Now().Add(pongWait))
  80. c.session.Conn.SetPongHandler(func(string) error {
  81. _ = c.session.Conn.SetReadDeadline(time.Now().Add(pongWait))
  82. return nil
  83. })
  84. for {
  85. _, data, err := c.session.Conn.ReadMessage()
  86. if err != nil {
  87. c.isConnected.Store(false)
  88. for c.connect() != nil {
  89. time.Sleep(reconnectWait)
  90. }
  91. continue
  92. }
  93. err = c.onReceive(data)
  94. if err != nil {
  95. c.onReceiveChan <- err
  96. }
  97. }
  98. }
  99. func (c *client) writeLoop() {
  100. for {
  101. msg := <-c.send
  102. _ = c.session.Conn.SetWriteDeadline(time.Now().Add(writeWait))
  103. if err := c.session.Conn.WriteMessage(websocket.BinaryMessage, msg); err != nil {
  104. continue
  105. }
  106. }
  107. }
  108. func (c *client) ping() {
  109. for range c.pingTicker.C {
  110. _ = c.session.Conn.SetWriteDeadline(time.Now().Add(writeWait))
  111. if err := c.session.Conn.WriteMessage(websocket.PingMessage, nil); err != nil {
  112. for c.connect() != nil {
  113. time.Sleep(reconnectWait)
  114. }
  115. }
  116. }
  117. }
  118. func (c *client) connect() error {
  119. conn, _, err := websocket.DefaultDialer.Dial(c.url.String(), c.requestHeader)
  120. if err != nil {
  121. return fmt.Errorf("dial: %s", err)
  122. }
  123. c.session = service.NewSession(conn)
  124. c.isConnected.Store(true)
  125. return nil
  126. }
  127. func (c *client) onReceive(msg []byte) error {
  128. _, msgPack, err := c.routerCodec.Unmarshal(msg)
  129. if err != nil {
  130. return fmt.Errorf("onreceive: %v", err)
  131. }
  132. router, ok := msgPack.Router.(string)
  133. if !ok {
  134. return fmt.Errorf("onreceive: invalid router:%v", msgPack.Router)
  135. }
  136. s, ok := c.handlers[router]
  137. if !ok {
  138. return fmt.Errorf("onreceive: function not registed router:%s err:%v", msgPack.Router, err)
  139. }
  140. var args = []reflect.Value{s.Receiver, reflect.ValueOf(c.session), reflect.ValueOf(msgPack.DataPtr)}
  141. s.Method.Func.Call(args)
  142. return nil
  143. }
  144. func (c *client) onSend(msg []byte) (err error) {
  145. defer func() {
  146. if e := recover(); e != nil {
  147. err = ErrBrokenPipe
  148. }
  149. }()
  150. if !c.isConnected.Load() {
  151. return ErrBrokenPipe
  152. }
  153. if len(c.send) >= maxSendBuffer {
  154. return ErrBufferPoolExceed
  155. }
  156. if len(msg) > maxFrameMessageLen {
  157. return
  158. }
  159. c.send <- msg
  160. return nil
  161. }
  162. func (c *client) Send(router string, data any) error {
  163. rb, err := c.routerCodec.Marshal(router, data, nil)
  164. if err != nil {
  165. return fmt.Errorf("service: %v", err)
  166. }
  167. return c.onSend(rb)
  168. }
  169. func (c *client) OnReceiveError() <-chan error {
  170. return c.onReceiveChan
  171. }
  172. func (c *client) Connect(requestHeader http.Header) error {
  173. c.requestHeader = requestHeader
  174. err := c.connect()
  175. if err != nil {
  176. return err
  177. }
  178. go c.ping()
  179. go c.writeLoop()
  180. go c.readLoop()
  181. return nil
  182. }