使用 mosquitto 代理在 node.js 服务器中获取 mqtt 消息 header
Get mqtt message header in node.js server with mosquitto broker
如何使用 mosquitto 代理在 mqtt 消息中获取 header 代理或 device/browser 详细信息。我的 mqtt 代码示例:
var mqtt = require('mqtt');
var client = mqtt.connect('mqtt://127.0.0.1:1883',{
username: 'xxxx',
password: 'xxxx'
});
client.on('connect', function (err,done) {
if(err){
console.log(err)
}else{
console.log("Connected...")
client.subscribe('test');
}
})
client.on('message', function (topic, message) {
// want to get the header details here.
})
除了 MQTT 消息的消息负载和主题之外,您无法获得任何其他信息,因为消息格式中不包含其他信息。这是设计使然,在 Pub/Sub 消息传递中,唯一重要的是主题和有效负载,而不是发送者。
on('message',function(){})
回调可以采用第 3 个参数,即原始 mqtt-packet 对象。您可以在文档 here 中查看可用数据的完整列表。但唯一的额外信息是关于重复状态、qos 以及消息是否保留。
client.on('message',function(topic, message, mqtt-packet) {
...
});
如果您需要更多信息,您需要手动将其包含在客户端自己发布的消息负载中。
如何使用 mosquitto 代理在 mqtt 消息中获取 header 代理或 device/browser 详细信息。我的 mqtt 代码示例:
var mqtt = require('mqtt');
var client = mqtt.connect('mqtt://127.0.0.1:1883',{
username: 'xxxx',
password: 'xxxx'
});
client.on('connect', function (err,done) {
if(err){
console.log(err)
}else{
console.log("Connected...")
client.subscribe('test');
}
})
client.on('message', function (topic, message) {
// want to get the header details here.
})
除了 MQTT 消息的消息负载和主题之外,您无法获得任何其他信息,因为消息格式中不包含其他信息。这是设计使然,在 Pub/Sub 消息传递中,唯一重要的是主题和有效负载,而不是发送者。
on('message',function(){})
回调可以采用第 3 个参数,即原始 mqtt-packet 对象。您可以在文档 here 中查看可用数据的完整列表。但唯一的额外信息是关于重复状态、qos 以及消息是否保留。
client.on('message',function(topic, message, mqtt-packet) {
...
});
如果您需要更多信息,您需要手动将其包含在客户端自己发布的消息负载中。