阿里云微服务消息队列Token C# 设备端示例Demo-阿里云开发者社区

开发者社区> 云服务技术课堂> 正文

阿里云微服务消息队列Token C# 设备端示例Demo

简介: 微消息队列 MQTT 版的客户端收发消息时,服务端会根据 MQTT 客户端设置的 Username 和 Password 参数来进行鉴权。目前支持ak,sk通过签名方式认证,也支持通过Token方式进行认证。本文主要介绍基于:Token 使用NET SDK进行设备端连接认证。

Step By Step

1、Token获取

阿里云微服务消息队列Token C# Code Sample

2、Mqtt SDK安装
图片.png

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、测试效果
图片.png

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
    图片.png

更多参考

阿里云微服务消息队列Token C# Code Sample
阿里云微服务消息队列Token Java Code Sample
Demo 工程

版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。

分享:

云服务技术课堂,各类技术课程、最佳实践输出,来好好听课吧!

官方博客