如何使用Paho MQTT javascript客户端连接IBM Watson IOT?

时间:2017-04-06 11:36:07

标签: javascript ibm-cloud mqtt iot watson-iot

我正在尝试使用Paho MQTT Javascript客户端连接IBM Watson IoT平台,如下面的示例代码所示。

 
 var client = new Messaging.Client("myOqgId.messaging.internetofthings.ibmcloud.com", 8883, "myclientid_" + parseInt(Math.random() * 100, 10));

 //Gets  called if the websocket/mqtt connection gets disconnected for any reason
 client.onConnectionLost = function (responseObject) {
     //Depending on your scenario you could implement a reconnect logic here
     alert("connection lost: " + responseObject.errorMessage);
 };

 //Gets called whenever you receive a message for your subscriptions
 client.onMessageArrived = function (message) {
     //Do something with the push message you received
     $('#messages').append('<span>Topic: ' + message.destinationName + '  | ' + message.payloadString + '</span><br/>');
 };

 //Connect Options
 var options = {
     userName: API-Key here,
     password: Auth token here,
     timeout: 3,
     //Gets Called if the connection has sucessfully been established
     onSuccess: function () {
         alert("Connected");
     },
     //Gets Called if the connection could not be established
     onFailure: function (message) {
         alert("Connection failed: " + message.errorMessage);
     }
 };

 //Creates a new Messaging.Message Object and sends it to the HiveMQ MQTT Broker
 var publish = function (payload, topic, qos) {
     //Send your message (also possible to serialize it as JSON or protobuf or just use a string, no limitations)
     var message = new Messaging.Message(payload);
     message.destinationName = topic;
     message.qos = qos;
     client.send(message);
 }

但无法连接。 我收到此错误: 与'ws://myOrgIdXYZ.messaging.internetofthings.ibmcloud.com:8883 / mqtt'的WebSocket连接失败:WebSocket握手期间出错:net :: ERR_CONNECTION_RESET

请那些尝试使用Paho Mqtt客户端连接IBM Watson IoT的人。

1 个答案:

答案 0 :(得分:5)

谢谢大家的回复。基于我在代码中做出的所有回复。

&#13;
&#13;
 NSString*FileName=[asset valueForKey:@"filename"];
 NSLog(@"File name %@",FileName);

Its done.

Note: Accepted answer takes lots of time to load a phasset but it works.
&#13;
&#13;
&#13;

您可以看到我在ClientId中进行了更改。如果您不使用Watson IoT库,IBM Watson Iot将仅接受以下格式的客户ID。

var clientId = &#39; a:OrgId:&#39; + RandomString;

如果您使用的是IBM Watson IoT库,则客户端ID可以是任何内容。甚至我在node.js中实现了