作者:俏巴
概述
前面分别介绍了基于开源MQTT Client Java及Python语言连接阿里云物联网平台的示例,这里使用M2Mqtt Client C#进行测试,结合自定义Topic演示消息的上下行。
操作步骤
1、安装M2Mqtt
2、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);
}
}
}
签名方式的获取参考链接。
3、消息上行查看
4、下行消息测试
更多参考
C#语言.NET平台接入
基于开源JAVA MQTT Client连接阿里云IoT
阿里云物联网平台Qucik Start
基于开源Python MQTT Client连接阿里云IoT