前面分別介紹了基於開源MQTT Client Java及Python語言鏈接阿里雲物聯網平臺的示例,這裏使用M2Mqtt Client C#進行測試,結合自定義Topic演示消息的上下行。git
一、安裝M2Mqtt
github
二、Code sample測試
using System; using System.Text; using uPLibrary.Networking.M2Mqtt; using uPLibrary.Networking.M2Mqtt.Messages; namespace MQTTDemo { class Program { //private MqttClient client; static void Main(string[] args) { string ServerUrl = "*****.iot-as-mqtt.cn-shanghai.aliyuncs.com"; string UserName = "******"; string Password = "******"; string clientId = "******"; ConnectMqtt(ServerUrl, clientId, UserName, Password); Console.ReadKey(); } static void ConnectMqtt(string targetServer, string mqttClientId, string mqttUserName, string mqttPassword) { MqttClient client = new MqttClient(targetServer); client.ProtocolVersion = MqttProtocolVersion.Version_3_1_1; client.Connect(mqttClientId, mqttUserName, mqttPassword, false, 60); client.MqttMsgPublishReceived += Client_MqttMsgPublishReceived; // 在產品控制檯建立對應的自定義Topic,而後在設備Topic列表便可獲取 string PubTopic = "/******/******/user/Data1"; string SubTopic = "/******/******/user/Data2"; // 發佈消息到自定義Topic string content = "{'content':'msg from :" + mqttClientId + ", Hello World'}"; var id = client.Publish(PubTopic, Encoding.UTF8.GetBytes(content)); // 從自定義Topic訂閱消息 client.Subscribe(new string[] { SubTopic }, new byte[] { 0 }); } /// <summary> /// 設置訂閱回調 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> static void Client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e) { // handle message received string topic = e.Topic; string message = Encoding.UTF8.GetString(e.Message); Console.WriteLine("Device receive message topic :" + topic + " ,the message body is " + message); } } }
簽名方式的獲取參考連接。阿里雲
三、消息上行查看url
四、下行消息測試
spa
C#語言.NET平臺接入
基於開源JAVA MQTT Client鏈接阿里雲IoT
阿里雲物聯網平臺Qucik Start
基於開源Python MQTT Client鏈接阿里雲IoTcode
》》阿里雲雙11領億元補貼,拼手氣抽iPhone 11 Pro、衛衣等好禮,點此參與:http://t.cn/Ai1hLLJTblog
閱讀原文ci
本文爲雲棲社區原創內容,未經容許不得轉載。get