【问题标题】:how to disconnect from mqtt server using eclipse paho javascript client如何使用 eclipse paho javascript 客户端断开与 mqtt 服务器的连接
【发布时间】: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

标签: mqtt paho


【解决方案1】:

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

根据 Paho 文档调用 disconnect()

【讨论】:

  • 当有人解决了他们自己的问题然后花时间将它作为答案发布在此处供未来的读者使用时,这总是很好的。这对我有用,谢谢!
【解决方案2】:

你可以使用。

mqttClient.end();

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    相关资源
    最近更新 更多