什么是Mosca
Mosca是MQTT在Node.js中的一个Broker的开源实现,通俗讲也就是MQTT中的Server实现。 同时作者也维护着MQTT.js这一模块,这一模块大家可理解为MQTT的Client实现。
代码
在这里我们将演示一下离线消息发送,在这里我们采用的是zeroMQ最为订阅发布模型 Client pub
1 2 3 4 5 6 7 8 9
| var mqtt = require('mqtt');
var client = mqtt.createClient(5112, '182.92.149.22');
//client.subscribe('presence'); var num = 0; setInterval(function (){ client.publish('order', 'Hello mqtt ' + (num++),{qos:1, retain: true}); }, 1000);
|
Client Sub
1 2 3 4 5 6 7 8 9
| var mqtt = require('mqtt');
var client = mqtt.createClient(5112, 'localhost',{clientId:'1',clean:false});
client.subscribe('test',{qos:1});
client.on('message', function (topic, message) { console.log(message); });
|
Mosca Server
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| var mosca = require('mosca') var settings = { port: 5112, backend:{ type: 'zmq', json: false, zmq: require("zmq"), port: "tcp://127.0.0.1:33333", controlPort: "tcp://127.0.0.1:33334", delay: 5 }, persistence:{ factory: mosca.persistence.Mongo, url: "mongodb://localhost:27017/mosca" } }; var server = new mosca.Server(settings); server.on('ready', function(){ console.log('Mosca server is up and running'); }); server.on('published', function(packet, client) { console.log('Published', packet.payload); });
|
在上面我们看到我们使用zeromq作为发布订阅模型, mongodb作为持久化Db