-1

I have an application in which am connecting to a mqtt server i followed this link and made some more modifications and made a connection with a username and password,how to disconnect from that server

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import { Paho} from 'ng2-mqtt/mqttws31';

/*
  Generated class for the MqttService provider.

  See https://angular.io/docs/ts/latest/guide/dependency-injection.html
  for more info on providers and Angular 2 DI.
*/
@Injectable()
export class Mqttservice {
  
  client :any;
  message :any;
  topic : any ;
  user:any;
  
 
   constructor(public http: Http) {}


 connectToMqtt(user,pwd){
  this.client = new Paho.MQTT.Client("iot.eclipse.org",9001,user);
    this.client.onConnectionLost = this.onConnectionLost;
  this.client.onMessageArrived = this.onMessageArrived.bind(this);
    // connect the client
    this.client.connect({onSuccess:this.onConnect.bind(this),userName:user,password:Pwd});
 }

 // called when the client connects
  onConnect() {
     console.log("onConnect");
   }
  
 
   //subscribe to a topic
   subscribe(topic){
    this.topic = topic ;
    this.client.subscribe(this.topic);
        console.log("subscribed to a topic");
   }
   //send a message 
   publish(topic,msg){
    this.topic = topic ;
    this.message = new Paho.MQTT.Message(msg);
    this.message.destinationName = this.topic;
    this.client.send(this.message);
 
   }
  
 // called when the client loses its connection
  onConnectionLost(responseObject) {
    console.log("connection is lost");
    if (responseObject.errorCode !== 0) {
       console.log("onConnectionLost:"+responseObject.errorMessage);
      }
   }

 // called when a message arrives
  onMessageArrived(message) {
     console.log("message is from topic: "+message.destinationName);
 
 }


}

how to disconnect from server using disconnect() just like publish() or subscribe() that I used in code sample

hardillb
  • 54,545
  • 11
  • 67
  • 105
Lisa
  • 655
  • 3
  • 10
  • 34
  • Please try and make an effort to read the doc before posting, the Paho documentation clearly points how a function that will disconnect the client. – hardillb Mar 31 '17 at 17:46
  • yeah, i could have looked in to the Paho documentation thankyou@hardillb – Lisa Apr 03 '17 at 05:09

2 Answers2

3

disconnect() {
      console.log("client is disconnecting..");
      this.client.disconnect();
 }

just call the disconnect() as per the Paho documentation

Lisa
  • 655
  • 3
  • 10
  • 34
  • It's always good when someone solves their own problem then takes the time to post it as an answer here for future readers. This worked for me, thanks! – uhoh Dec 09 '18 at 06:42
1

You can use.

mqttClient.end();

Find details here : https://github.com/mqttjs/MQTT.js/

sharmag
  • 189
  • 2
  • 7