阿里云物联网平台Node.js SDK接入示例

本文介绍使用Node.js语言的AMQP SDK接入阿里云物联网平台,接收服务端订阅消息的示例。

开发环境

本示例所使用的开发环境为Node.js 8.0.0及以上版本。

下载SDK

Node.js版本AMQP SDK,推荐使用rhea。请访问rhea下载库和查看使用说明。

添加依赖

package.json中添加以下依赖。

"dependencies": {
    "rhea": "^1.0.12"
 }

代码示例

以下Demo中涉及的参数说明,请参见AMQP客户端接入说明。

const container = require('rhea');
const crypto = require('crypto');

//Create Connection
var connection = container.connect({
    'host': '${uid}.iot-amqp.${regionId}.aliyuncs.com',
    'port': 5671,
    'transport':'tls',
    'reconnect':true,
    'idle_time_out':60000,
    'username':'${YourClientId}|authMode=aksign,signMethod=hmacsha1,timestamp=1573489088171,authId=${YourAccessKeyID},consumerGroupId=${YourConsumerGroupId}|',
    'password': hmacSha1('${YourAccessKeySecret}', 'authId=${YourAccessKeyID}&timestamp=1573489088171'),
});

//Create Receiver Link
var receiver = connection.open_receiver();

//handle received message
container.on('message', function (context) {
    var msg = context.message;
    var messageId = msg.message_id;
    var topic = msg.application_properties.topic;
    var content = Buffer.from(msg.body.content).toString();

    //ACK
    context.delivery.accept();
});

//calculate password
function hmacSha1(key, context) {
    return Buffer.from(crypto.createHmac('sha1', key).update(context).digest())
        .toString('base64');
}

原创文章,作者:网友投稿,如若转载,请注明出处:https://www.cloudads.cn/archives/33387.html

发表评论

登录后才能评论