我正在尝试实现pub / sub,如下所示
publisher.js
var zmq = require('zmq');
var pub = zmq.socket('pub');
pub.bindSync('tcp://127.0.0.1:5555');
pub.send('pub msg');
/*
setInterval(function(){
console.log("sending message")
},500);*/
subscriber.js
var zmq = require('zmq');
var sub = zmq.socket('sub');
sub.connect('tcp://127.0.0.1:5555');
sub.subscribe(''); //herein lies the question
sub.on('message',function(msg){
console.log('Received msg:',msg);
})
只有当pub.send('pub msg');
在setInterval内部且不确定我的理解时,上述订阅者才会收到该消息
我不想使用setInterval而是我必须在收到消息后立即发送消息
请说我怎么能用pub / sub做这件事我想有一些基本的理解缺失请帮助
在nodejs代码中我尝试使用路径
router.post('/putMsgIn0MQ', function (req, res, next) {
pushData(JSON.stringify(req.body))
})
var pushData = function(dataToPush) {
var zmqSocket = zmq.socket('pub')
var zmqPortPart = 'tcp://127.0.0.1:5555'
zmqSocket.bind(zmqPortPart);
zmqSocket.send(dataToPush);
}
订户
var sub = zmq.socket('sub');
sub.connect('tcp://127.0.0.1:5555');
sub.subscribe(''); //herein lies the question
console.log('Received msg:');
sub.on('message',function(msg){
console.log('Received msg:');
console.log(msg.toString())
var jsonPayload = msg.toString();
processData(jsonPayload, zmqPortObj.name);
})
答案 0 :(得分:0)
基于此代码,来自他们的文档:
// pubber.js
var zmq = require('zmq')
, sock = zmq.socket('pub');
sock.bindSync('tcp://127.0.0.1:3000');
console.log('Publisher bound to port 3000');
setInterval(function(){
console.log('sending a multipart message envelope');
sock.send(['kitty cats', 'meow!']);
}, 500);
似乎setInterval只是效用函数:)
什么阻止您手动触发?
例如,假想的控制器:
exports.animals= {
getCat: function (request, response) {
var animal = request.payload.catStuff;
//process the animal object
//and manually fire the message like:
sock.send(['kitty cats', 'meow!']);
...