我正在尝试使用 M2MQTT 库将 MQTT 消息发送到 Azure IoT 中心。我已遵循此处的指导 IoT Hub MQTT support在该文章的 native MQTT 部分中提供正确的连接参数等。
我使用以下代码成功连接(CONNACK 返回值 0):
_publishClient = new MqttClient(_hostName, 8883, true, null, null,MqttSslProtocols.TLSv1_2);
_publishClient.MqttMsgPublished += _client_MqttMsgPublished;
_publishClient.ConnectionClosed += _client_ConnectionClosed;
var connack = _publishClient.Connect(_publishDeviceId, string.Format("{0}/{1}",
_hostName, _publishDeviceId), _publishSas,true,3600);
但是一旦我发出发布调用(其中 deviceid 是我的设备 ID):
var pubresult = _publishClient.Publish("/devices/{deviceid}/messages/events/", Encoding.UTF8.GetBytes("Hello"), MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE, false);
M2MQTT 断开连接并引发 OnConnectionClosed 事件,并且消息永远不会传递到 Azure IoT 中心。
我尝试逐步退出 M2MQTT MqttClient 类代码,断开连接来自 ReceiveThread,注释听起来像是 Azure IoT Hub 端关闭了连接:
// zero bytes read, peer gracefully closed socket
else
{
// wake up thread that will notify connection is closing
this.OnConnectionClosing();
}
如果有人对它关闭的原因或如何排除故障有任何想法,我会洗耳恭听。
最佳答案
您可能想要删除发布主题字符串中的第一个“/”,而不是
var pubresult = _publishClient.Publish("/devices/{deviceid}/messages/events/", Encoding.UTF8.GetBytes("Hello"), MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE, false);
使用
var pubresult = _publishClient.Publish("devices/{deviceid}/messages/events/", Encoding.UTF8.GetBytes("Hello"), MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE, false);
这是对此建议的page ,并且对我有效。
关于azure - M2MQTT 在发布时断开与 Azure IoT 中心的连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38423213/