如何使用eclipse paho javascript client

时间:2017-03-31 14:53:58

标签: mqtt paho

我有一个应用程序,它连接到mqtt服务器i followed this link 并进行了一些修改,并使用用户名和密码建立连接,如何断开与该服务器的连接

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);
 
	}


}

如何使用disconnect()断开与服务器的连接,就像我在代码示例中使用的publish()或subscribe()

2 个答案:

答案 0 :(得分:1)

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

  

根据Paho文档

调用disconnect()

答案 1 :(得分:1)

您可以使用。

mqttClient.end();

在此处查找详细信息: https://github.com/mqttjs/MQTT.js/