简体   繁体   中英

Cannot connect to MQTT broker(mosquitto) with Javascript Ionic

I tried to bind MQTT with the Ionic framework. When trying to send an MQTT message to the broker (I am publishing), when a click event occurs, I get the following error:

"AMQJS0011E Invalid state not connected......" "WebSocket connection to 'ws://test.mosquitto.org:8080/mqtt' failed: Error >during WebSocket handshake: net::ERR_CONNECTION_RESET"

Please can anyone help me? I cannot find a solution anywhere.

I also tried with port 1883, but the problem remains the same.

var App = angular.module("App",["ionic","ngWebSocket"]);

App.controller("Appctrl",["$scope","$log",Appctrl]);

function Appctrl($scope,$log,$websocket){

$scope.mqtt_on = function() {

   client = new Paho.MQTT.Client("test.mosquitto.org",    
   Number(8080),"zsrgdxrgdt");
   client.connect();
   message = new Paho.MQTT.Message("Hello");
   message.destinationName = "test/smit";
   client.send(message);
   alert("ON");
};

$scope.mqtt_off = function() {
   alert("Off");
`enter code here`};

};

The Paho Javascript client is asynchronous, the connect function will return before the connection is complete

So the call to send is being made before the connection is complete.

The connect function can take a argument which can contain a callback function to call once the connection is complete. So something like this should work

client.connect({onSuccess: function(){
  message = new Paho.MQTT.Message("Hello");
  message.destinationName = "test/smit";
  client.send(message);
}});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM