gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 02:44:17 24 4
gpt4 key购买 nike

我正在尝试使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com