Step By Step
1、Token获取
2、Mqtt SDK安装
3、Code Sample
using System;
using System.Text;
using uPLibrary.Networking.M2Mqtt;
using uPLibrary.Networking.M2Mqtt.Messages;
namespace DeviceDemo
{
class Program
{
static void Main(string[] args)
{
//实例 ID,购买后从控制台获取
string instanceId = "post-cn-6ja********";
//此处填写购买得到的 MQTT 接入点域名
string brokerUrl = "post-cn-6ja********.mqtt.aliyuncs.com";
//此处填写阿里云帐号 AccessKey
string accessKey = "LTAIOZZg********";
//此处填写在 MQ 控制台创建的 Topic,作为 MQTT 的一级 Topic
string parentTopic = "mqtt_topic_demo";
string token = "Lz11111111111Ohp/jsE3gf63H8bJGYgJWUr5piesdvDY0i8fNY68mR3UqN9LKVT5IGzKPvooOIjF1CZZ9uU74CT40m4bkmcftVUBP5SM+VepMKCyQgoJWL8b3AQUS1QPxDA2oGf+JBKuN0DyYW6d7mIYhAqXTpVbQw5nNCvKP80Xo0WYK9UHMgTMh9qdrn6MS1rwaP765dpXzvgHC9nWeHX7K80O6vtOU9M8Qn5VrhkP0F1umbOoYs3NfM+WYZIQx4pkViQo6qqkxgbD7le+3be3pCzYxaiucQ7FjZd54BvCYvrg==";
string clientId = "GID_MQTT_Group1@@@device1";
MqttClient client = new MqttClient(brokerUrl);
client.MqttMsgPublishReceived += client_recvMsg;
client.MqttMsgPublished += client_publishSuccess;
client.ConnectionClosed += client_connectLose;
//username和 Password 签名模式下的设置方法,参考文档 https://help.aliyun.com/document_detail/48271.html?spm=a2c4g.11186623.6.553.217831c3BSFry7
string userName = "Token|" + accessKey + "|" + instanceId;
string passWord = string.Format(@"RW|{0}", token);
client.Connect(clientId, userName, passWord, true, 60);
//订阅 Topic,支持多个 Topic,以及多级 Topic
string[] subTopicArray = { parentTopic + "/subDemo1", parentTopic + "/subDemo2/level3"};
//string[] subTopicArray = { parentTopic + "/#" };
byte[] qosLevels = { MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE, MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE };
client.Subscribe(subTopicArray, qosLevels);
client.Publish(parentTopic + "/subDemo1", Encoding.UTF8.GetBytes("hello mqtt"), MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE, false);
//发送 P2P 消息,二级 topic 必须是 p2p,三级 topic 是接收客户端的 clientId
client.Publish(parentTopic + "/p2p/" + clientId, Encoding.UTF8.GetBytes("hello p2p mqtt"), MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE, false);
Console.ReadKey();
}
static void client_recvMsg(object sender, MqttMsgPublishEventArgs e)
{
// access data bytes throug e.Message
Console.WriteLine("Recv Msg : Topic is " + e.Topic + " ,Body is " + Encoding.UTF8.GetString(e.Message));
}
static void client_publishSuccess(object sender, MqttMsgPublishedEventArgs e)
{
// access data bytes throug e.Message
Console.WriteLine("Publish Msg Success");
}
static void client_connectLose(object sender, EventArgs e)
{
// access data bytes throug e.Message
Console.WriteLine("Connect Lost,Try Reconnect");
}
}
}
4、测试效果
5、使用云端API向指定Topic发送消息
- 5.1 pom.xml
<!-- https://mvnrepository.com/artifact/com.aliyun/aliyun-java-sdk-onsmqtt -->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-onsmqtt</artifactId>
<version>1.0.4</version>
</dependency>
- 5.2 Java Code sample
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.google.gson.Gson;
import com.aliyuncs.onsmqtt.model.v20200420.*;
public class SendMessage {
public static void main(String[] args) {
DefaultProfile profile = DefaultProfile.getProfile("mq-internet-access", "LTAIOZZg********", "v7CjUJCMk7j9aK****************");
IAcsClient client = new DefaultAcsClient(profile);
SendMessageRequest request = new SendMessageRequest();
request.setRegionId("mq-internet-access");
request.setInstanceId("post-cn-6ja********");
request.setPayload("message from manager api!");
request.setMqttTopic("mqtt_topic_demo/subDemo1");
try {
SendMessageResponse response = client.getAcsResponse(request);
System.out.println(new Gson().toJson(response));
} catch (ServerException e) {
e.printStackTrace();
} catch (ClientException e) {
System.out.println("ErrCode:" + e.getErrCode());
System.out.println("ErrMsg:" + e.getErrMsg());
System.out.println("RequestId:" + e.getRequestId());
}
}
}
- 5.3 The Result
更多参考
阿里云微服务消息队列Token C# Code Sample
阿里云微服务消息队列Token Java Code Sample
Demo 工程