我使用的是NodeJS的mqtt
模块。一切正常,即发布、订阅特定主题、处理连接错误等。问题是,当我尝试订阅所有主题时,通常以client.subscribe('#',callback)
的形式完成,它不订阅任何主题。
这是相关代码:
// Connecting to a specific topic
client = mqtt.connect(broker,options)
console.log("MQTT Connected")
client.on('connect',()=>{
client.subscribe('mytopic/topic1',(err,granted)=>{
if(err){
console.log(err)
}
console.log(granted)
console.log("Subscribed to mytopic/topic1")
})
listenIncoming()
})
client.on('error',err=>{
console.log("ERROR in MQTT: ",err)
})
订阅所有主题的代码:
client = mqtt.connect(broker,options)
console.log("MQTT Connected")
client.on('connect',()=>{
client.subscribe('#',(err,granted)=>{
if(err){
console.log(err)
}
console.log(granted)
console.log("Subscribed to all topics")
})
listenIncoming()
})
client.on('error',err=>{
console.log("ERROR in MQTT: ",err)
})
这就是listenIncoming()
函数,它在收到消息时打印出消息:
function listenIncoming(){
client.on('message',(topic,payload,packet)=>{
var topics = subscribedTopics
console.log(topics,payload) //prints it when specific topic is subscribed. Doesn't when subscribing to '#'
})
}
如何使用此订阅所有主题?我使用的经纪人是hivemq(mqtt://broker.hivemq.com)
不允许在broker.hivemq.com上订阅#
。
通过使用mosquitto_sub
可以看出
$ mosquitto_sub -v -t '#' -h broker.hivemq.com
All subscription requests were denied.
或者,您的代码显示了128的qos(来自规范(。
$ node test.js
MQTT Connected
[ { topic: '#', qos: 128 } ]
Subscribed to all topics