javascript - 如何在nodeJS中使用 mqtt.Client(streamBuilder, options) 构造函数

标签 javascript node.js mqtt

我正在尝试使用 npm 包“mqtt.js”构建简单的 MQTT 应用程序。我尝试过 mqtt.connect() 构造函数,它工作正常,但我想探索 MQTT 的更多功能,因此我想使用 mqtt.client() 构造函数。官方文档没有示例,所以我很困惑。 这是我到目前为止所尝试过的
var mqtt = require('mqtt')

客户端1:-

var mqtt = require('mqtt')

client = mqtt.connect('http://localhost:1883',{clientId :'client1', clean: false});

  client.on('connect', function () {
    client.subscribe('presence',{QoS:2});
    client.subscribe('offline',{QoS:2});
    console.log('connected');
  });
  client.on('message', function (topic, message) {
    console.log(message.toString());
  });

客户端2:-

var mqtt = require('mqtt')

client = mqtt.connect('http://localhost:1883',{clientId :'client2', clean: false,will:{topic:'offline',payload:'off',qos:2}});

   client.on('connect', function () {
    client.publish('presence', '{message:hello,id:1}',{QoS:2});

  });

任何例子都会有帮助。
谢谢。

最佳答案

您可以直接在 connect() 调用中传递客户端连接选项,如以下代码片段所示:

// Connect with unique clientId and set clean to false, so as to receive any
// missed QOS 1 or 2 messages received at broker when this worker was down.
this.MqttClient = mqtt.connect(this.tls_url,{clientId : this.myClientId, clean: false});

this.MqttClient.on('connect', function(connack){
    // do stufff       
});

关于javascript - 如何在nodeJS中使用 mqtt.Client(streamBuilder, options) 构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48165996/

相关文章:

javascript - 查找数组中最长的单词 JavaScript

javascript - 我如何知道应该在 NodeJS 中使用哪些参数

node.js - Visual Studio 代码调试 Node.JS NOENT : no such file or directory when debugging with MongoDB

azure - 将 azure 连接到外部 mqtt 代理

amazon-web-services - 从 Lambda 向 AWS IoT Core 发布 MQTT 消息

javascript - ionic 推送无法读取未定义的属性 'init'

相机的 javascript 操纵杆

javascript - 使用 2 个不同的按钮在同一位置切换 2 个 Div

javascript - Node.JS 如何处理重复的传递依赖?

c++ - libmosquittopp - 示例客户端在 loop_stop() 方法上挂起