saas-smartAi通信协议标准库
gongshangguo
2022-03-02 d13ed6d79af61db6333ad5cc3200d96b6410d064
client/client.go
@@ -6,6 +6,7 @@
   "bufio"
   "encoding/binary"
   "encoding/json"
   "errors"
   uuid "github.com/satori/go.uuid"
   "go.uber.org/zap"
   "io"
@@ -22,8 +23,6 @@
   DefaultHeartbeatInterval = 15 * time.Second
   // 读取数据超时时间
   DefaultReaderTimeOut = 60 * time.Second
   // 连接尝试间隔
   DefaultNetRetry = 10 * time.Second
)
// 连接状态
@@ -37,8 +36,6 @@
   // 已断开
   StateDisconnected
)
var syncReq map[string]chan *aiot.Protocol
// 连接状态
type State int32
@@ -233,7 +230,7 @@
   }
   // 发送消息
   c.WriteBody(body)
   _ = c.WriteBody(body)
   return body, nil
}
@@ -243,6 +240,12 @@
         c.Logger.Error("Write Body Error:", err)
      }
   }()
   if c.IsClosed() {
      errMsg := "Can not write msg into closed chain"
      c.Logger.Warn(errMsg, zap.Any("msg",body))
      return errors.New(errMsg)
   }
   body.Receiver = aiot.RECEIVER_TO_SAAS
   msgData, err := json.Marshal(body)
   if err != nil {
@@ -435,6 +438,11 @@
   return c.deviceId
}
// 获取连接状态
func (c *Client) GetState() State {
   return c.state
}
// 判断连接是否关闭
func (c *Client) IsClosed() bool {
   return c.state == StateDisconnected
@@ -452,17 +460,18 @@
// 关闭TCP
func (c *Client) Close() {
   c.Logger.Debug("Closing connect", zap.String("addr", c.addr))
   c.Logger.Debug("Closing connect...", zap.String("addr", c.addr))
   c.closeLock.Lock()
   defer c.closeLock.Unlock()
   // 关闭通道
   if !c.IsClosed() {
      c.Conn.Close()
      _ = c.Conn.Close()
      if c.IsConnected() {
         c.clientCallback.OnClose(c)
      }
      // 设置连接属性
      c.SetState(StateDisconnected)
   }
   // 设置连接属性
   c.SetState(StateDisconnected)
   c.Logger.Debug("Connect closed...", zap.String("addr", c.addr))
}