2017-03-31 81 views
-1

我有一個應用程序,其中連接到一個mqtt服務器i followed this link並作了一些修改,並與用戶名和密碼連接,如何從該服務器斷開連接如何斷開與mqtt服務器使用Eclipse paho javascript客戶端

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; 
 
    
 
    
 
    \t constructor(public http: Http) {} 
 

 

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

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

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

 

 
}

如何從服務器斷開連接使用(),像發佈()斷開或認購(),我的代碼示例中使用

+0

請嘗試並努力在發佈前先閱讀文檔,泛美衛生組織文件明確指出如何在功能,將斷開客戶端。 – hardillb

+0

是的,我可以看看Paho文檔謝謝@ hardillb – Lisa

回答

0

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

只需調用斷開()按照泛美衛生組織文檔

相關問題