【发布时间】:2017-03-31 14:53:57
【问题描述】:
我有一个应用程序正在连接到 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() 一样
【问题讨论】:
-
请在发帖前努力阅读文档,Paho 文档清楚地指出了如何断开客户端连接。
-
是的,我本可以查看 Paho 文档thankyou@hardillb