Step By Step
1、Token擷取
阿裡雲微服務消息隊列Token C# Code Sample
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# 裝置端示例Demo