/// <summary> /// 断开连接 /// </summary> public void DisConnect() { try { #region 先取消订阅 List <string> topics = new List <string>(); if (Client.Subscriptions.Count > 0) { foreach (Subscription subscription in Client.Subscriptions) { topics.Add(subscription.TopicName); } string errMsg = string.Empty; UnSubscribe(topics, ref errMsg); } #endregion Client.MessageReceived -= OnMessageReceived; Client.ReconnectedMqtt -= OnReconnectedMqtt; Client.Disconnect(); Client.Dispose(); LogHelper.WriteDebug("MQTT连接断开"); } catch (Exception e) { LogHelper.WriteError("MQTT连接断开失败" + e.Message); } }
/// <summary> /// 方法说明:MQTT断开连接 /// 完成时间:2016-04-20 /// </summary> public void DisConnect() { try { if (_client == null) { return; } //先取消主题的订阅 var topics = new List <string>(); if (_client.Subscriptions.Count > 0) { topics.AddRange(_client.Subscriptions.Select(subscription => subscription.TopicName)); var errMsg = string.Empty; UnSubscribe(topics, ref errMsg); } //再取消事件订阅 _client.MessageReceived -= OnMessageReceived; _client.ReconnectedMqtt -= OnReconnectedMqtt; //最后断开断开连接 _client.Disconnect(); //断开连接后,心跳计数需要释放 _heartbeattimer.Close(); _heartbeatnumber = 0; _client.Dispose(); LogHelper.WriteDebug(Resources.SdkMqttDisconnectSuccess); } catch (Exception ex) { LogHelper.WriteError($"{Resources.SdkMqttDisconnectFail}:{ex.Message}"); } }