我们设置了一个由MQTT.js提供支持的 MQTT 客户端(在桌面 PC 上或在实际板上,都是一样的)和一个由mosca提供支持的 MQTT 代理,这个代理在桌面 PC 上运行。
我们能够成功地从客户端向代理发送具有特定主题的消息,但现在我们陷入了相反的境地:从代理向客户端发送消息。
我们正在遵循两个项目文档中提供的代码示例,但没有运气。客户端能够正确注册到主题,但在发送消息时不会以任何方式做出反应。Broker 能够正确发送消息,也能够监听自己的消息,因为它无论如何都在监听所有消息。
摘自 MQTT 代理:
broker.on('published', function(packet, client) {
console.log('MQTT broker received message'); // it passes by here
console.log(' - packet:', packet);
console.log(' - packet payload:', packet.payload.toString());
});
// ...
var packet = {
topic: 'our_custom_topic',
payload: ourCustomPayload,
qos: 1,
retain: false,
};
console.log('MQTT broker sending message to client ...');
broker.publish(packet, function() {
console.log('Message sent'); // it passes by here
});
摘自 MQTT 客户端:
client.on('connect', function () {
console.log('MQTT client connected');
client.subscribe('our_custom_topic', { qos: 1 }, function onSubscribe(err, granted) {
if (err) {
console.log('subscribe errors:', err); // no error shown
}
if (granted) {
console.log('subscribe granted:', granted); // it passes by here
}
});
});
// ...
client.on('message', function (topic, message, packet) {
console.log('MQTT client received message'); // it DOESN'T pass by here
console.log(' - topic', topic);
console.log(' - message', JSON.stringify(message));
console.log(' - packet', JSON.stringify(packet));
});
更新
当持久性基于 mongoDb 时,问题似乎就出现了。相反,当持久性基于内存时,消息会正确发送给订阅者。以下是依赖 mongoDb 持久性时的 pub-sub 设置。实际上,它是一个在 mongolab.com 上运行的开发实例:
var mongoDbSettings = {
// remote MongoLab mongodb instance
url: 'mongodb://mqtt-db-user:<OUR-USER-CODE>@<THEIR-INSTANCE-SUBDOMAIN>.mongolab.com:39291/sample-mqtt-datastore',
pubsubCollection: 'myCollections',
};
var mongoDbBrokerSettings = {
port: 1883, // mosca (mqtt) port
// using ascoltatore over MongoDB
backend: {
type: 'mongo',
url: mongoDbSettings.url,
pubsubCollection: mongoDbSettings.pubsubCollection,
mongo: {},
},
persistence: {
factory: mosca.persistence.Mongo,
url: mongoDbSettings.url,
}
};
var broker = new mosca.Server(mongoDbBrokerSettings, function onCreated(err, broker) {
// assume no errors
console.log('MQTT broker is up and running');
});
有人发现这有什么问题吗?