在 ZMQ 请求-回复模式中侦听 connect/connection 事件

Listening for connect/connection events within ZMQ request-reply pattern

在 ZMQ 请求-回复模式的回复者或 'server' 中,我想监听连接到我的 replier/server 的请求者。

我有这个代码:

    var zmqConfig = {...};
    var replier = zmq.socket('rep');

    var address = 'tcp://'.concat(zmqConfig.host).concat(':').concat(zmqConfig.port);

    replier.bind(address, function (err) {
        if (err) {

        }
    });

        replier.on('message', function () {
         // this is firing
         });

        replier.on('connect',function(){
         // but this is NOT firing
       });

       replier.on('connection',function(){
        // neither is this
       });

但我的请求者确实正在连接并向我的回复者发送消息,如下所示:

       var requester = zmq.socket('req');
       requester.connect('tcp://...'); // this should invoke the connect/connection event above???

"connect" 事件在连接的一侧触发,这不是您要查找的内容。您想要的是 "accept" 事件,当绑定的套接字接受来自对等方的新连接时会触发该事件。

要捕获此事件,您必须在连接发生之前在您的套接字上调用 monitor() 方法...大概在您 bind() 您的套接字之前。您放入 monitor() 方法中的计时器不会影响它触发的事件,只会影响它触发它们的时间。

这是您修改后的代码,以这种方式工作:

var zmqConfig = {...};
var replier = zmq.socket('rep');
replier.monitor(50); // just picked a time

var address = 'tcp://'.concat(zmqConfig.host).concat(':').concat(zmqConfig.port);

replier.bind(address, function (err) {
    if (err) {

    }
});

replier.on('message', function () {
    // this is firing
});

replier.on('accept', function(){
    // this should *now* fire when you accept a connection from a peer
});