node.js – 如何使用AWS IoT向/從Web瀏覽器傳送/接收訊息
我們正在嘗試使用Amazon Web Services物聯網(AWS IoT)從Web瀏覽器傳送訊息(例如:鑑於AWS IoT支援JavaScript,我們預計這是可能的…
我們在AWS IoT文件中搜索,但只找到伺服器端示例(它暴露了AWS金鑰/金鑰…)
是否有任何良好的工作示例或教程使用AWS IoT通過Socket/">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", "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" ] } ] }
程式碼日誌版權宣告:
翻譯自:http://stackoverflow.com/questions/35439742/how-to-use-aws-iot-to-send-receive-messages-to-from-web-browser