monitor.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // Copyright 2019 autocareai.com. All rights reserved.
  2. // Use of this source code is governed by autocareai.com.
  3. package tcp_packet
  4. import (
  5. "context"
  6. dust "dust-monitor/handler/v1"
  7. "dust-monitor/util"
  8. "fmt"
  9. "go.uber.org/zap"
  10. "net"
  11. "github.com/jaryhe/gopkgs/logger"
  12. "time"
  13. )
  14. func monitorDataHandel(src []byte) (err error) {
  15. // 解析数据帧
  16. frame := util.DustFrameParse(src)
  17. err = dust.DustDataHandle(context.Background(), &frame)
  18. return err
  19. }
  20. func HandleSocketClient(conn net.Conn) {
  21. // 处理完后关闭连接
  22. defer conn.Close()
  23. request := make([]byte, 1024)
  24. var gleft, result []byte
  25. var isComplete bool
  26. for {
  27. read_len, err := conn.Read(request)
  28. fmt.Printf("dust once read:length:%v, err:%v, bytes:%s\n", read_len, err, request[:read_len])
  29. start := time.Now().UnixNano()
  30. if err != nil {
  31. logger.Error("dust read start error",
  32. zap.String("client", conn.RemoteAddr().String()),
  33. zap.String("err", err.Error()),
  34. zap.String("msg", string(request[:read_len])),
  35. zap.String("timestamp", fmt.Sprintf("%d", start)))
  36. break
  37. } else {
  38. logger.Info("dust read start",
  39. zap.String("client", conn.RemoteAddr().String()),
  40. zap.String("msg", string(request[:read_len])),
  41. zap.String("timestamp", fmt.Sprintf("%d", start)))
  42. }
  43. gleft = append(gleft, request[:read_len]...)
  44. for {
  45. result, gleft, isComplete, err = util.DustParse(gleft[:])
  46. if err != nil {
  47. return
  48. }
  49. // 包没有读完继续读取数据包
  50. if isComplete == false {
  51. break
  52. }
  53. fmt.Printf("complete bytes:%s\n", result)
  54. // 处理数据
  55. err = monitorDataHandel(result)
  56. end := time.Now().UnixNano()
  57. if err != nil {
  58. logger.Error("dust handle over error",
  59. zap.String("client", conn.RemoteAddr().String()),
  60. zap.String("error", err.Error()),
  61. zap.String("bytes", string(result)),
  62. zap.String("timediff",fmt.Sprintf("%d", end-start)),
  63. zap.String("timestamp", fmt.Sprintf("%d", end)))
  64. } else {
  65. logger.Info("dust handle over",
  66. zap.String("client", conn.RemoteAddr().String()),
  67. zap.String("timediff",fmt.Sprintf("%d", end-start)),
  68. zap.String("timestamp", fmt.Sprintf("%d", end)))
  69. }
  70. }
  71. }
  72. }