websoket.models.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. package common
  2. import (
  3. "fmt"
  4. "log"
  5. "time"
  6. // api "git.eugeniocarvalho.dev/eugeniucarvalho/apicodegen/api"
  7. // "git.eugeniocarvalho.dev/eugeniucarvalho/apicodegen/api/errs"
  8. // "github.com/davecgh/go-spew/spew"
  9. "github.com/gorilla/websocket"
  10. // bson "go.mongodb.org/mongo-driver/bson"
  11. // "go.mongodb.org/mongo-driver/bson/primitive"
  12. )
  13. var (
  14. visits uint64
  15. newline = []byte{'\n'}
  16. space = []byte{' '}
  17. )
  18. type Event struct {
  19. Kind string `json:"kind"`
  20. ThreadID string `json:"thread,omitempty"`
  21. SectionID string `json:"section,omitempty"`
  22. UserId string `json:"-"`
  23. Payload string `json:"payload,omitempty"`
  24. Entity interface{} `json:"-"`
  25. Date time.Time `json:"date"`
  26. }
  27. const (
  28. // Time allowed to write a message to the peer.
  29. writeWait = 10 * time.Second
  30. // Time allowed to read the next pong message from the peer.
  31. pongWait = 60 * time.Second
  32. // Send pings to peer with this period. Must be less than pongWait.
  33. pingPeriod = (pongWait * 9) / 10
  34. // Maximum message size allowed from peer.
  35. maxMessageSize = 512
  36. )
  37. type WsClient struct {
  38. Id string
  39. Hub *Hub
  40. // The websocket connection.
  41. Conn *websocket.Conn
  42. // Buffered channel of outbound messages.
  43. // Send chan []byte
  44. Send chan *Event
  45. }
  46. // Hub maintains the set of active Clients and Broadcasts messages to the
  47. // Clients.
  48. type Hub struct {
  49. // Registered Clients.
  50. Clients map[string]*WsClient
  51. // Inbound messages from the Clients.
  52. Broadcast chan *Event
  53. Inbound chan *Event
  54. EventHandlers map[string]func(*Hub, *Event)
  55. // Register requests from the WsClient.
  56. Register chan *WsClient
  57. // Unregister requests from WsClient.
  58. Unregister chan *WsClient
  59. }
  60. func NewHub() *Hub {
  61. return &Hub{
  62. Broadcast: make(chan *Event),
  63. Inbound: make(chan *Event),
  64. Register: make(chan *WsClient),
  65. Unregister: make(chan *WsClient),
  66. Clients: make(map[string]*WsClient),
  67. EventHandlers: map[string]func(*Hub, *Event){
  68. },
  69. }
  70. }
  71. // func (control *ThreadCtrl) RegisterClient(client *WsClient) {
  72. // for _, member := range *(control.Thread.Members) {
  73. // if member.Id == client.Id {
  74. // control.Clients[client.Id] = client
  75. // break
  76. // }
  77. // }
  78. // }
  79. // func tsyncHandler(hub *Hub, event *Event) {
  80. // // ctrl, err := hub.GetThread(event.ThreadID)
  81. // // if err != nil {
  82. // // fmt.Println(err)
  83. // // return
  84. // // }
  85. // // for _, cli := range ctrl.Clients {
  86. // // if cli.Id != event.UserId {
  87. // // cli.Send <- event
  88. // // }
  89. // // }
  90. // }
  91. func (hub *Hub) Run() {
  92. for {
  93. select {
  94. case client := <-hub.Register:
  95. // Se o cliente possui uma conexão. Encerra e seta o novo cliente
  96. // if c, found := hub.Clients[client.Id]; found {
  97. // hub.Unregister <- c
  98. // }
  99. // fmt.Println("register client ", client)
  100. hub.Clients[client.Id] = client
  101. case client := <-hub.Unregister:
  102. if _, ok := hub.Clients[client.Id]; ok {
  103. delete(hub.Clients, client.Id)
  104. close(client.Send)
  105. }
  106. case event := <-hub.Inbound:
  107. // fmt.Println("runing dispatch ", event)
  108. hub.dispatch(event)
  109. case event := <-hub.Broadcast:
  110. // spew.Dump(hub.Clients)
  111. for ID, client := range hub.Clients {
  112. // fmt.Println("broadcast to client")
  113. select {
  114. case client.Send <- event:
  115. default:
  116. delete(hub.Clients, ID)
  117. close(client.Send)
  118. }
  119. }
  120. }
  121. }
  122. }
  123. func (h *Hub) dispatch(event *Event) {
  124. fmt.Println("dispatch", event)
  125. if fn, found := h.EventHandlers[event.Kind]; found {
  126. fn(h, event)
  127. } else {
  128. //TODO register erro
  129. }
  130. }
  131. func (c *WsClient) Handle() {
  132. go c.WriteHandler()
  133. go c.ReadHandler()
  134. }
  135. func (c *WsClient) ReadHandler() {
  136. var (
  137. // payload []byte
  138. err error
  139. event *Event
  140. hub = c.Hub
  141. )
  142. defer func() {
  143. // fmt.Println("FINALIZANDO ReadHandler()")
  144. if err != nil {
  145. if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
  146. log.Printf("error: %v", err)
  147. }
  148. }
  149. hub.Unregister <- c
  150. c.Conn.Close()
  151. }()
  152. // c.Conn.SetReadLimit(maxMessageSize)
  153. // c.Conn.SetReadDeadline(time.Now().Add(pongWait))
  154. // c.Conn.SetPongHandler(func(string) error { c.Conn.SetReadDeadline(time.Now().Add(pongWait)); return nil })
  155. for {
  156. event = &Event{}
  157. if err = c.Conn.ReadJSON(event); err != nil {
  158. break
  159. }
  160. fmt.Println("read payload")
  161. // spew.Dump(event)
  162. event.UserId = c.Id
  163. hub.Inbound <- event
  164. }
  165. }
  166. func (c *WsClient) WriteHandler() {
  167. var (
  168. // ticker = time.NewTicker(pingPeriod)
  169. // message []byte
  170. err error
  171. )
  172. defer func() {
  173. if err != nil {
  174. c.Conn.WriteMessage(websocket.CloseMessage, []byte{})
  175. }
  176. // fmt.Println("FINALIZANDO WriteHandler()")
  177. // ticker.Stop()
  178. c.Conn.Close()
  179. }()
  180. for {
  181. select {
  182. case event, ok := <-c.Send:
  183. // spew.Dump(event)
  184. fmt.Println("write message", !ok)
  185. // c.Conn.SetWriteDeadline(time.Now().Add(writeWait))
  186. if !ok {
  187. err = fmt.Errorf("0000000000")
  188. return
  189. }
  190. if err = c.Conn.WriteJSON(event); err != nil {
  191. return
  192. }
  193. // case <-ticker.C:
  194. // // c.Conn.SetWriteDeadline(time.Now().Add(writeWait))
  195. // if err := c.Conn.WriteMessage(websocket.PingMessage, nil); err != nil {
  196. // return
  197. // }
  198. // }
  199. }
  200. }
  201. }