client.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. package server
  2. import (
  3. "AT-Server/netAtSDK"
  4. "github.com/gogf/gf/encoding/gbinary"
  5. "github.com/gogf/gf/net/gtcp"
  6. "github.com/gogf/gf/os/glog"
  7. "io"
  8. "net"
  9. "strings"
  10. "sync"
  11. "syscall"
  12. "time"
  13. )
  14. const defaultPassword = "0000"
  15. type Client struct {
  16. Id string
  17. srv *Server
  18. conn *gtcp.Conn
  19. closeChan chan struct{}
  20. closeHandler func(id string, c *Client)
  21. onReg func(id string, c *Client)
  22. isReg bool
  23. mu sync.Mutex
  24. waitingATResp bool
  25. atClient *netAtSDK.ATClient
  26. sendChan chan []byte
  27. }
  28. func NewClient(s *Server, conn *gtcp.Conn) *Client {
  29. return &Client{
  30. srv: s,
  31. conn: conn,
  32. atClient: netAtSDK.NetATClient(conn, defaultPassword),
  33. closeChan: make(chan struct{}),
  34. }
  35. }
  36. func (c *Client) SetId(id string) {
  37. c.Id = id
  38. }
  39. func (c *Client) ReadLoop() {
  40. for {
  41. select {
  42. case <-c.closeChan:
  43. return
  44. default:
  45. buf, err := c.conn.Recv(-1)
  46. if err != nil {
  47. c.readError(err)
  48. glog.Error(c.srv.ctx, err.Error())
  49. return
  50. }
  51. if len(buf) > 0 {
  52. if !c.isReg {
  53. id := gbinary.DecodeToString(buf)
  54. c.SetId(id)
  55. c.isReg = true
  56. if c.onReg != nil {
  57. c.onReg(c.Id, c)
  58. }
  59. return
  60. }
  61. }
  62. }
  63. }
  64. }
  65. func (c *Client) readError(err error) {
  66. defer c.closeConnection()
  67. if err == io.EOF || isErrConnReset(err) {
  68. return
  69. }
  70. glog.Errorf("读取数据发生错误:%s", err.Error())
  71. }
  72. func (c *Client) closeConnection() {
  73. _ = c.conn.Close()
  74. c.conn = nil
  75. close(c.closeChan)
  76. c.isReg = false
  77. if c.closeHandler != nil {
  78. c.closeHandler(c.Id, c)
  79. }
  80. }
  81. // isErrConnReset read: connection reset by peer
  82. func isErrConnReset(err error) bool {
  83. if ne, ok := err.(*net.OpError); ok {
  84. return strings.Contains(ne.Err.Error(), syscall.ECONNRESET.Error())
  85. }
  86. return false
  87. }
  88. func (c *Client) send(buf []byte) error {
  89. if c.conn == nil {
  90. return nil
  91. }
  92. glog.Debugf("----->%2X", buf)
  93. err := c.conn.Send(buf)
  94. if err != nil {
  95. glog.Error(c.srv.ctx, err)
  96. c.closeConnection()
  97. return err
  98. }
  99. return nil
  100. }
  101. func (c *Client) Test() {
  102. time.Sleep(60 * time.Second)
  103. str, err := c.atClient.GetAll()
  104. if err != nil {
  105. glog.Debugf("查询出错:%s", err)
  106. }
  107. glog.Debugf("查询结果 :%s", str)
  108. }