client.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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. onReceive(msg []byte) error
  35. onSend(msg []byte) (err error)
  36. Send(router string, data any) error
  37. Connect(requestHeader http.Header) error
  38. OnReceiveError() <-chan error
  39. Disconnect()
  40. }
  41. type client struct {
  42. url url.URL
  43. requestHeader http.Header
  44. logger *zap.Logger
  45. session *service.Session
  46. isConnected *atomic.Bool
  47. routerCodec codec.Codec
  48. send chan []byte
  49. handlers map[string]*service.Handler // 注册的方法列表
  50. onReceiveChan chan error
  51. pingTicker *time.Ticker
  52. }
  53. func New(logger *zap.Logger, url url.URL, decoder string, handlers interface{}) (Client, error) {
  54. if !assist.InArray(url.Scheme, []string{"ws", "wss"}) {
  55. return nil, errors.New(`param: scheme not supported`)
  56. }
  57. routerCodec := codec.GetCodec(decoder)
  58. if routerCodec == nil {
  59. return nil, errors.New(`param: codec not supported`)
  60. }
  61. components := service.RegisterHandler(handlers)
  62. if len(components) == 0 {
  63. return nil, errors.New(`param: handlers unqualified`)
  64. }
  65. c := &client{
  66. logger: logger,
  67. isConnected: new(atomic.Bool),
  68. routerCodec: routerCodec,
  69. url: url,
  70. send: make(chan []byte, maxSendBuffer),
  71. handlers: components,
  72. onReceiveChan: make(chan error, maxSendBuffer),
  73. pingTicker: time.NewTicker(pingPeriod),
  74. }
  75. return c, nil
  76. }
  77. func (c *client) readLoop() {
  78. defer func() {
  79. c.logger.Sugar().Info("readLoop closed")
  80. }()
  81. _ = c.session.Conn.SetReadDeadline(time.Now().Add(pongWait))
  82. c.session.Conn.SetPongHandler(func(string) error {
  83. _ = c.session.Conn.SetReadDeadline(time.Now().Add(pongWait))
  84. return nil
  85. })
  86. c.logger.Sugar().Info("readLoop running")
  87. for c.session.Conn != nil {
  88. _, data, err := c.session.Conn.ReadMessage()
  89. if err != nil {
  90. c.isConnected.Store(false)
  91. for c.connect() != nil {
  92. time.Sleep(reconnectWait)
  93. }
  94. continue
  95. }
  96. err = c.onReceive(data)
  97. if err != nil {
  98. c.onReceiveChan <- err
  99. }
  100. }
  101. }
  102. func (c *client) writeLoop() {
  103. defer func() {
  104. c.logger.Sugar().Info("writeLoop closed")
  105. }()
  106. c.logger.Sugar().Info("writeLoop running")
  107. for {
  108. select {
  109. case msg := <-c.send:
  110. _ = c.session.Conn.SetWriteDeadline(time.Now().Add(writeWait))
  111. if err := c.session.Conn.WriteMessage(websocket.BinaryMessage, msg); err != nil {
  112. break
  113. }
  114. }
  115. }
  116. }
  117. func (c *client) ping() {
  118. for range c.pingTicker.C {
  119. _ = c.session.Conn.SetWriteDeadline(time.Now().Add(writeWait))
  120. if err := c.session.Conn.WriteMessage(websocket.PingMessage, nil); err != nil {
  121. for c.connect() != nil {
  122. time.Sleep(reconnectWait)
  123. }
  124. }
  125. }
  126. }
  127. func (c *client) connect() error {
  128. conn, _, err := websocket.DefaultDialer.Dial(c.url.String(), c.requestHeader)
  129. if err != nil {
  130. return fmt.Errorf("dial: %s", err)
  131. }
  132. c.session = service.NewSession(conn)
  133. c.isConnected.Store(true)
  134. return nil
  135. }
  136. func (c *client) onReceive(msg []byte) error {
  137. _, msgPack, err := c.routerCodec.Unmarshal(msg)
  138. if err != nil {
  139. return fmt.Errorf("onreceive: %v", err)
  140. }
  141. router, ok := msgPack.Router.(string)
  142. if !ok {
  143. return fmt.Errorf("onreceive: invalid router:%v", msgPack.Router)
  144. }
  145. s, ok := c.handlers[router]
  146. if !ok {
  147. return fmt.Errorf("onreceive: function not registed router:%s err:%v", msgPack.Router, err)
  148. }
  149. var args = []reflect.Value{s.Receiver, reflect.ValueOf(c.session), reflect.ValueOf(msgPack.DataPtr)}
  150. s.Method.Func.Call(args)
  151. return nil
  152. }
  153. func (c *client) onSend(msg []byte) (err error) {
  154. defer func() {
  155. if e := recover(); e != nil {
  156. err = ErrBrokenPipe
  157. }
  158. }()
  159. if !c.isConnected.Load() {
  160. return ErrBrokenPipe
  161. }
  162. if len(c.send) >= maxSendBuffer {
  163. return ErrBufferPoolExceed
  164. }
  165. if len(msg) > maxFrameMessageLen {
  166. return
  167. }
  168. c.send <- msg
  169. return nil
  170. }
  171. func (c *client) Send(router string, data any) error {
  172. rb, err := c.routerCodec.Marshal(router, data, nil)
  173. if err != nil {
  174. return fmt.Errorf("service: %v", err)
  175. }
  176. return c.onSend(rb)
  177. }
  178. func (c *client) OnReceiveError() <-chan error {
  179. return c.onReceiveChan
  180. }
  181. func (c *client) Connect(requestHeader http.Header) error {
  182. c.requestHeader = requestHeader
  183. err := c.connect()
  184. if err != nil {
  185. return err
  186. }
  187. go c.ping()
  188. go c.writeLoop()
  189. go c.readLoop()
  190. return nil
  191. }
  192. func (c *client) Disconnect() {
  193. c.pingTicker.Stop()
  194. _ = c.session.Conn.Close()
  195. close(c.send)
  196. close(c.onReceiveChan)
  197. c.session.Conn = nil
  198. }