client.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. package server
  2. import (
  3. "dlt645-server/protocol"
  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. "syscall"
  11. "time"
  12. )
  13. type Client struct {
  14. Id string
  15. srv *Server
  16. conn *gtcp.Conn
  17. sendChan chan []byte
  18. closeChan chan struct{}
  19. closeHandler func(id string, c *Client)
  20. lastHeartBeat time.Time
  21. done chan struct{}
  22. gatewayId uint16
  23. isReg bool
  24. }
  25. func (c *Client) ReadLoop() {
  26. //defer c.srv.grWG.Done()
  27. for {
  28. buf, err := c.conn.Recv(-1)
  29. if err != nil {
  30. c.readError(err)
  31. return
  32. }
  33. if len(buf) > 0 {
  34. if !c.isReg {
  35. id := gbinary.DecodeToString(buf)
  36. glog.Debugf("收到注册包!id:%s", id)
  37. c.SetId(id)
  38. c.isReg = true
  39. continue
  40. }
  41. err = c.srv.message.Decode(buf)
  42. if err != nil {
  43. glog.Errorf("解析报文失败:%s", err.Error())
  44. }
  45. }
  46. }
  47. }
  48. func (c *Client) SetId(id string) {
  49. c.Id = id
  50. }
  51. func (c *Client) readError(err error) {
  52. defer c.closeConnection()
  53. if err == io.EOF || isErrConnReset(err) {
  54. return
  55. }
  56. glog.Errorf("读取数据发生错误:%s", err.Error())
  57. }
  58. func (c *Client) closeConnection() {
  59. _ = c.conn.Close()
  60. c.conn = nil
  61. close(c.done)
  62. c.SetId("")
  63. c.isReg = false
  64. if c.closeHandler != nil {
  65. c.closeHandler(c.Id, c)
  66. }
  67. }
  68. // isErrConnReset read: connection reset by peer
  69. func isErrConnReset(err error) bool {
  70. if ne, ok := err.(*net.OpError); ok {
  71. return strings.Contains(ne.Err.Error(), syscall.ECONNRESET.Error())
  72. }
  73. return false
  74. }
  75. func (c *Client) send(buf []byte) error {
  76. if c.conn == nil {
  77. return nil
  78. }
  79. err := c.conn.Send(buf)
  80. if err != nil {
  81. glog.Error(err)
  82. c.closeConnection()
  83. return err
  84. }
  85. glog.Debugf("指令发送成功:%2X", buf)
  86. return nil
  87. }
  88. func (c *Client) Send0X3433() {
  89. //defer c.srv.grWG.Done()
  90. entity := protocol.Dlt_0x33333433{}
  91. entity.DeviceAddress = []byte{0x27, 0x12, 0x03, 0x14, 0x07, 0x22}
  92. for {
  93. sendByte, _ := entity.Encode()
  94. err := c.send(sendByte)
  95. if err != nil {
  96. glog.Debugf("指令发送失败:%s", err.Error())
  97. }
  98. time.Sleep(10 * time.Second)
  99. }
  100. }
  101. func (c *Client) SendAddress() {
  102. defer c.srv.grWG.Done()
  103. for {
  104. bytea := []byte{0x68, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0x68, 0x13, 0x00, 0xDF, 0x16}
  105. c.send(bytea)
  106. time.Sleep(5 * time.Second)
  107. }
  108. }