aws 消息转发服务器,node.js – 如何使用AWS IoT向/从Web浏览器发送/接收消息

本文档展示了如何使用JavaScript中的AWS Cognito身份池来获取凭证,并连接到AWS IoT Data服务进行设备身份验证。通过配置Cognito Identity Pool,获取AWS凭证,然后使用这些凭证签署请求URL以连接到MQTT代理。接着,初始化MQTT客户端,订阅特定主题并发布消息。IAM角色的权限设置允许设备订阅和发布到指定的MQTT主题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这是一个使用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",

"Resource": "*"

},

{

"Effect": "Allow",

"Action": "iot:Subscribe",

"Resource": [

"arn:aws:iot:us-east-1::your/mqtt/topic"

]

},

{

"Effect": "Allow",

"Action": "iot:Publish",

"Resource": [

"arn:aws:iot:us-east-1::your/mqtt/topic"

]

}

]

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值