Node.js   发布时间:2022-04-24  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了node.js – 如何使用AWS IoT向/从Web浏览器发送/接收消息大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。



我们正在尝试使用Amazon Web services物联网(AWS IoT)从Web浏览器发送消息(例如:鉴于AWS IoT支持JavaScript,我们预计这是可能的…

我们在AWS IoT文档中搜索,但只找到服务器端示例(它暴露了AWS密钥/密钥…)

是否有任何良好的工作示例或教程使用AWS IoT通过WebSockets / MQTT在浏览器中发送/接收消息(例如:使用AWS Cognito进行身份验证)?谢谢!

解决方法

这是一个使用JS中的认知标识池来连接,发布和对订阅做出反应的示例.

// Configure Cognito identity pool
AWs.config.region = 'us-east-1';
var credentials = new AWs.CognitoIdentityCredentials({
    IdentityPoolId: 'us-east-1:your identity pool guid',});

// GetTing AWS creds from Cognito is async,so we need to drive the rest of the mqtt client initialization in a callBACk
credentials.get(function(err) {
    if(err) {
        console.log(err);
        return;
    }
    var requesturl = SigV4Utils.getSignedUrl('wss','data.iot.us-east-1.amazonaws.com','/mqtt','iotdevicegateway','us-east-1',credentials.accessKeyId,credentials.secretAccessKey,credentials.sessionToken);
    initClient(requesturl);
});

function init() {
  // do setup stuff
}

// Connect the client,subscribe to the drawing topic,and publish a "hey I connected" message
function initClient(requesturl) {
    var clientId = String(Math.random()).replace('.','');
    var client = new Paho.MQTT.Client(requesturl,clientId);
    var connectOptions = {
        onsuccess: function () {
            console.log('connected');

            // subscribe to the drawing
            client.subscribe("your/mqtt/topic");

            // publish a lifecycle event
            message = new Paho.MQTT.message('{"id":"' + credentials.identityId + '"}');
            message.desTinationName = 'your/mqtt/topic';
            console.log(messagE);
            client.send(messagE);
        },useSSL: true,timeout: 3,mqttVersion: 4,onFailure: function () {
            console.error('connect Failed');
        }
    };
    client.connect(connectOptions);

    client.onmessageArrived = function (messagE) {

        try {
            console.log("msg arrived: " +  message.payloadString);
        } catch (E) {
            console.log("error! " + E);
        }

    };
}

请记住,授权您的IAM角色也可以订阅/发布.以下是一个例:

{
    "Version": "2012-10-17","Statement": [
        {
            "Effect": "Allow","Action": [
                "iot:Connect"
            ],"resource": "*"
        },{
            "Effect": "Allow","Action": "iot:receive","Action": "iot:Subscribe","resource": [
                "arn:aws:iot:us-east-1::your/mqtt/topic"
            ]
        },"Action": "iot:Publish","resource": [
                "arn:aws:iot:us-east-1::your/mqtt/topic"
            ]
        }
    ]
}

大佬总结

以上是大佬教程为你收集整理的node.js – 如何使用AWS IoT向/从Web浏览器发送/接收消息全部内容,希望文章能够帮你解决node.js – 如何使用AWS IoT向/从Web浏览器发送/接收消息所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。