client.go 4.7 KB

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