C#代码实现阿里云消息服务MNS消息监听

Wesley13
• 阅读 708

十年河东,十年河西,莫欺少年穷

学无止境,精益求精

近几天一直都在看阿里云的IOT云服务及消息队列MNS,一头雾水好几天了,直到今天,总算有点收获了,记录下来,方便以后查阅。

首先借用阿里云的一张图来说明:设备是如何通过云服务平台和企业服务器‘通话的’

C#代码实现阿里云消息服务MNS消息监听

针对此图,作如下说明:

1、物联网平台作为中间组件,主要是通过消息队MNS列来实现设备和企业服务器对话的,具体可描述为:

1.1、设备发送指令至物联网平台的MNS队列,MNS队列将设备指令收录,需要说明的是:设备发送指令是通过嵌入式开发人员开发的,例如C语言

1.2、企业通过C#、JAVA、PHP等高级语言开发人员开发监听程序,当监听到MNS队列中的设备指令时,获取指令,做相关业务处理,并发送新的设备指令至MNS队列。【例如发送快递柜关门的指令】

1.3、企业发送的指令被MNS收录,设备同样通过监听程序获取企业服务器发送的关门指令,收到关门指令的设备执行相关指令,完成自动关门操作。

以上便是设备与企业服务器之间的对话过程

下面列出C#的监听MNS代码【需要MNS C# JDK 的支持】注意:消息是经过EncodeBase64编码,接受消息要解码,发送消息要编码

异步监听:

C#代码实现阿里云消息服务MNS消息监听 C#代码实现阿里云消息服务MNS消息监听

using System;
using System.Threading;
using System.Threading.Tasks;
using Aliyun.MNS;
using Aliyun.MNS.Model;
using IotCommon;
using IotDtos.MongodbDtos;
using IotService.Device;
using IotService.MongoDb;

namespace IotListener
{
    class Program
    {
        private static MongoLogService _logService;
        public static string _receiptHandle;
        public static DeviceResponseService service = new DeviceResponseService();
        public static Queue nativeQueue;
        static void Main(string[] args)
        {
            LogstoreDatabaseSettings st = new LogstoreDatabaseSettings() { LogsCollectionName = "LogsForDg_" + DateTime.Now.ToString("yyyyMMdd") };
            _logService = new MongoLogService(st);
            while (true)
            {
                try
                {
                    IMNS client = new Aliyun.MNS.MNSClient(IotParm._accessKeyId, IotParm._secretAccessKey, IotParm._endpoint, IotParm._stsToken);
                    nativeQueue = client.GetNativeQueue(IotParm._queueName);
                    for (int i = 0; i < IotParm._receiveTimes; i++)
                    {
                        ReceiveMessageRequest request = new ReceiveMessageRequest(1);
                        nativeQueue.BeginReceiveMessage(request, ListenerCallback, null);
                        Thread.Sleep(1);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Receive message failed, exception info: " + ex.Message);
                }
            }
        }

        /// <summary>
        /// 回调函数
        /// </summary>
        /// <param name="ar"></param>
        public static void ListenerCallback(IAsyncResult ar)
        {
            try
            {
                Message message = nativeQueue.EndReceiveMessage(ar).Message;
                string Json = Base64Helper.DecodeBase64(message.Body);
                Console.WriteLine("Message: {0}", Json);
                Console.WriteLine("----------------------------------------------------\n");
                var methodValue = JsonKeyHelper.GetJsonValue(Json, "method");
                DeviceResponse(methodValue, Json);
                if (!string.IsNullOrEmpty(methodValue))
                {
                    _logService.Create(new LogsForDgModel { CreateTime = DateTime.Now, data = Json, methodNo = methodValue });
                }
                _receiptHandle = message.ReceiptHandle;
                nativeQueue.DeleteMessage(_receiptHandle);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Receive message failed, exception info: " + ex.Message);
            }

        }

        /// <summary>
        /// 响应设备上传接口
        /// </summary>
        /// <param name="method"></param>
        /// <param name="message"></param>
        public static void DeviceResponse(string method, string message)
        {
            switch (method)
            {
                case "doorClosedReport": service.doorClosedReportResponse(message); break;
                case "doorOpenReport": service.doorOpenReportResponse(message); break;
                case "deviceStartReportToCloud": service.deviceStartReportToCloudResponse(message); break;
                case "qryDeviceConfig": service.qryDeviceConfigResponse(message); break;
                case "devicePingToCloud": service.devicePingToCloudResponse(message); break;
                case "deviceFatalReport": service.deviceFatalReportResponse(message); break;
                case "deviceVersionReport": service.deviceVersionReportResponse(message); break;
                case "deviceFirmwareData": service.deviceFirmwareDataResponse(message); break;
                case "deviceLocationReport": service.deviceLocationReportResponse(message); break;
            }
        }
    }
}

View Code

同步监听:

C#代码实现阿里云消息服务MNS消息监听 C#代码实现阿里云消息服务MNS消息监听

using Aliyun.MNS;
using Aliyun.MNS.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace MnsListener
{
    class Program
    {
        #region Private Properties
        private const string _accessKeyId = "";
        private const string _secretAccessKey = "";
        private const string _endpoint = "http://.mns.cn-shanghai.aliyuncs.com/";
        private const string _stsToken = null;

        private const string _queueName = "Sub";
        private const string _queueNamePrefix = "my";
        private const int _receiveTimes = 1;
        private const int _receiveInterval = 2;
        private const int batchSize = 6;
        private static string _receiptHandle;

        #endregion


        static void Main(string[] args)
        {
            while (true)
            {
                try
                {
                    IMNS client = new Aliyun.MNS.MNSClient(_accessKeyId, _secretAccessKey, _endpoint, _stsToken);
                    var nativeQueue = client.GetNativeQueue(_queueName);
                    for (int i = 0; i < _receiveTimes; i++)
                    {
                        var receiveMessageResponse = nativeQueue.ReceiveMessage(3);
                        Console.WriteLine("Receive message successfully, status code: {0}", receiveMessageResponse.HttpStatusCode);
                        Console.WriteLine("----------------------------------------------------");
                        Message message = receiveMessageResponse.Message;
                        string s = DecodeBase64(message.Body);
                        Console.WriteLine("MessageId: {0}", message.Id);
                        Console.WriteLine("ReceiptHandle: {0}", message.ReceiptHandle);
                        Console.WriteLine("MessageBody: {0}", message.Body);
                        Console.WriteLine("MessageBodyMD5: {0}", message.BodyMD5);
                        Console.WriteLine("EnqueueTime: {0}", message.EnqueueTime);
                        Console.WriteLine("NextVisibleTime: {0}", message.NextVisibleTime);
                        Console.WriteLine("FirstDequeueTime: {0}", message.FirstDequeueTime);
                        Console.WriteLine("DequeueCount: {0}", message.DequeueCount);
                        Console.WriteLine("Priority: {0}", message.Priority);
                        Console.WriteLine("----------------------------------------------------\n");

                        _receiptHandle = message.ReceiptHandle;
                        nativeQueue.DeleteMessage(_receiptHandle);

                        Thread.Sleep(_receiveInterval);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Receive message failed, exception info: " + ex.Message);
                }
            }

        }

        ///编码
        public static string EncodeBase64(string code, string code_type= "utf-8")
        {
            string encode = "";
            byte[] bytes = Encoding.GetEncoding(code_type).GetBytes(code);
            try
            {
                encode = Convert.ToBase64String(bytes);
            }
            catch
            {
                encode = code;
            }
            return encode;
        }
        ///解码
        public static string DecodeBase64(string code, string code_type = "utf-8")
        {
            string decode = "";
            byte[] bytes = Convert.FromBase64String(code);
            try
            {
                decode = Encoding.GetEncoding(code_type).GetString(bytes);
            }
            catch
            {
                decode = code;
            }
            return decode;
        }
    }
}

View Code

发送消息:

C#代码实现阿里云消息服务MNS消息监听 C#代码实现阿里云消息服务MNS消息监听

using Aliyun.MNS;
using Aliyun.MNS.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace MnsSendMsg
{
    class Program
    {
        #region Private Properties
        private const string _accessKeyId = "";
        private const string _secretAccessKey = "";
        private const string _endpoint = "http://.mns.cn-shanghai.aliyuncs.com/";
        private const string _stsToken = null;

        private const string _queueName = "Sub";
        private const string _queueNamePrefix = "my";
        private const int _receiveTimes = 1;
        private const int _receiveInterval = 2;
        private const int batchSize = 6;
        private static string _receiptHandle;
        #endregion
        static void Main(string[] args)
        {
            try
            {
                IMNS client = new Aliyun.MNS.MNSClient(_accessKeyId, _secretAccessKey, _endpoint, _stsToken);
                // 1. 获取Queue的实例
                var nativeQueue = client.GetNativeQueue(_queueName);
                var sendMessageRequest = new SendMessageRequest(EncodeBase64("阿里云<MessageBody>计算"));
                sendMessageRequest.DelaySeconds = 2;
                var sendMessageResponse = nativeQueue.SendMessage(sendMessageRequest);
                Console.WriteLine("Send message successfully,{0}",
                    sendMessageResponse.ToString());
                Thread.Sleep(2000);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Send message failed, exception info: " + ex.Message);
            }
        }

        ///编码
        public static string EncodeBase64(string code, string code_type = "utf-8")
        {
            string encode = "";
            byte[] bytes = Encoding.GetEncoding(code_type).GetBytes(code);
            try
            {
                encode = Convert.ToBase64String(bytes);
            }
            catch
            {
                encode = code;
            }
            return encode;
        }
        ///解码
        public static string DecodeBase64(string code, string code_type = "utf-8")
        {
            string decode = "";
            byte[] bytes = Convert.FromBase64String(code);
            try
            {
                decode = Encoding.GetEncoding(code_type).GetString(bytes);
            }
            catch
            {
                decode = code;
            }
            return decode;
        }
    }
}

View Code

关于MNS C# JDK下载,可以去阿里云:https://help.aliyun.com/document_detail/32447.html?spm=a2c4g.11186623.6.633.61395f64IfHTRo

关于MNS队列,主题,主题订阅相关知识:https://help.aliyun.com/document_detail/34445.html?spm=a2c4g.11186623.6.542.699f38c6RO3nDS

关于阿里云AMQP队列接入,可以查询:https://help.aliyun.com/document_detail/149716.html?spm=a2c4g.11186623.6.621.2cda31b4kS1zXR

关于阿里云物联网平台,请查阅:https://help.aliyun.com/document_detail/125800.html?spm=a2c4g.11186623.6.542.7b0241c8o5r6PT

最后:阿里云物联网平台

@天才卧龙的博客

点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
待兔 待兔
5个月前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Jacquelyn38 Jacquelyn38
3年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
Peter20 Peter20
3年前
mysql中like用法
like的通配符有两种%(百分号):代表零个、一个或者多个字符。\(下划线):代表一个数字或者字符。1\.name以"李"开头wherenamelike'李%'2\.name中包含"云",“云”可以在任何位置wherenamelike'%云%'3\.第二个和第三个字符是0的值wheresalarylike'\00%'4\
Wesley13 Wesley13
3年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
3年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
3年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
11个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这