zmq nodejs模块推拉不能正常工作。订户没有正确接收消息

时间:2014-03-19 06:20:14

标签: node.js sockets zeromq

我在nodejs中有一个zmq发布者和订阅者代码。我的问题是我的订阅者有时没有收到任何消息。我的代码是

出版商:

var zmq = require('zmq'),

socket = zmq.socket('push'),
socket.bind(publisherUrl, function (err) {
if (err) {
    console.log(err);
}
else {
    console.log("Listening on ..." + publisherUrl)
}

});

function PublishEvent(msg) {
setTimeout(function () {
    socket.send(msg);
}, 100);

}

订户:

var zmq = require('zmq'),
events = require('events'),
subscriber = zmq.socket('pull');

subscriber.on("message", function (reply) {
if (reply.toString() !== '{}'){
console.log("info", 'Received message:' + reply.toString());
}
})
subscriber.connect(publisherUrl)

它的工作正常,但在某些情况下无法接收消息。我被困在这里任何有关这方面的帮助都会有所帮助。

1 个答案:

答案 0 :(得分:1)

您的发布商应如下所示:

var zmq = require('zmq')
var publisher = zmq.socket('pub')

publisher.bind('tcp://*:8688', function(err) {
    if(err)
        console.log(err)
    else
        console.log("Listening on 8688...")
})

for (var i=1 ; i<10 ; i++)
    setTimeout(function() {
        console.log('sent');
        publisher.send("Hello there!")
}, 1000 * i)

process.on('SIGINT', function() {
    publisher.close()
    console.log('\nClosed')
})

您的订阅者应如下所示:

var zmq = require('zmq')
var subscriber = zmq.socket('sub')

subscriber.on("message", function(reply) {
    console.log('Received message: ', reply.toString());
})

subscriber.connect("tcp://localhost:8688")
subscriber.subscribe("")

process.on('SIGINT', function() {
    subscriber.close()
    console.log('\nClosed')
})

来源:https://github.com/imatix/zguide/tree/master/examples/Node.js