client.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package ws
  2. import (
  3. "github.com/go-admin-team/go-admin-core/logger"
  4. "github.com/gorilla/websocket"
  5. )
  6. // Client 单个 websocket 信息
  7. type Client struct {
  8. ID, Group string
  9. Socket *websocket.Conn
  10. Message chan []byte
  11. }
  12. // MessageData 单个发送数据信息
  13. type MessageData struct {
  14. ID, Group string
  15. Message []byte
  16. }
  17. // MessageDataString 单个发送数据信息
  18. type MessageDataString struct {
  19. ID, Group string
  20. Message string
  21. }
  22. // GroupMessageData 组广播数据信息
  23. type GroupMessageData struct {
  24. Group string
  25. Message []byte
  26. }
  27. // BroadCastMessageData 广播发送数据信息
  28. type BroadCastMessageData struct {
  29. Message []byte
  30. }
  31. // Read
  32. func (c *Client) Read() {
  33. defer func() {
  34. WebsocketManager.UnRegister <- c
  35. logger.Infof("client [%s] disconnect", c.ID)
  36. if err := c.Socket.Close(); err != nil {
  37. logger.Errorf("client [%s] disconnect err: %s", c.ID, err)
  38. }
  39. }()
  40. for {
  41. logger.Debug("in for Read handler")
  42. messageType, message, err := c.Socket.ReadMessage()
  43. if err != nil || messageType == websocket.CloseMessage {
  44. break
  45. }
  46. logger.Debugf("client [%s] receive message: %s", c.ID, string(message))
  47. c.Message <- message
  48. }
  49. }
  50. // Write 写信息,从 channel 变量 Send 中读取数据写入 websocket 连接
  51. func (c *Client) Write() {
  52. defer func() {
  53. WebsocketManager.UnRegister <- c //网络错误或客户端链接关闭,退出处理逻辑
  54. logger.Infof("client [%s] disconnect", c.ID)
  55. if err := c.Socket.Close(); err != nil {
  56. logger.Errorf("client [%s] disconnect err: %s", c.ID, err)
  57. }
  58. }()
  59. for {
  60. select {
  61. case message, ok := <-c.Message:
  62. if !ok {
  63. _ = c.Socket.WriteMessage(websocket.CloseMessage, []byte{})
  64. return
  65. }
  66. // logger.Debug("write message: ", message)
  67. err := c.Socket.WriteMessage(websocket.TextMessage, message)
  68. if err != nil {
  69. logger.Errorf("client [%s] writemessage err: %s", c.ID, err)
  70. }
  71. }
  72. }
  73. }