Retrieving subscriber count using zeromq PUB/SUB sockets

后端 未结 3 2188
温柔的废话
温柔的废话 2021-02-19 11:41

Is it possible to get the total count of subscribers from a PUB socket in zeromq?

Thanks!

3条回答
  •  再見小時候
    2021-02-19 11:54

    This is implementation on NodeJS for rep, I think for pub it's the same.

    Like Jakob Möllås said, need to use monitor.

    const zmq = require('zmq')
            , rep = zmq.socket('rep');
    
    let counter = 0;
    
    rep.bind('tcp://*:5560', function (err) {
        if (err) {
            console.log(err);
        } else {
            console.log("Listening on 5560…");
            rep.monitor(500, 0);
        }
    });
    
    // Register to monitoring events
    rep.on('connect', function (fd, ep) {
        console.log('connect, endpoint:', ep);
    });
    rep.on('connect_delay', function (fd, ep) {
        console.log('connect_delay, endpoint:', ep);
    });
    rep.on('connect_retry', function (fd, ep) {
        console.log('connect_retry, endpoint:', ep);
    });
    rep.on('listen', function (fd, ep) {
        console.log('listen, endpoint:', ep);
    });
    rep.on('bind_error', function (fd, ep) {
        console.log('bind_error, endpoint:', ep);
    });
    rep.on('accept', function (fd, ep) {
        console.log('accept, endpoint:', ep);
        counter++;
    });
    rep.on('accept_error', function (fd, ep) {
        console.log('accept_error, endpoint:', ep);
    });
    rep.on('close', function (fd, ep) {
        console.log('close, endpoint:', ep);
    });
    rep.on('close_error', function (fd, ep) {
        console.log('close_error, endpoint:', ep);
    });
    rep.on('disconnect', function (fd, ep) {
        console.log('disconnect, endpoint:', ep);
        counter--;
    });
    
    // Handle monitor error
    rep.on('monitor_error', function(err) {
        console.log('Error in monitoring: %s, will restart monitoring in 5 seconds', err);
        setTimeout(function() { rep.monitor(500, 0); }, 5000);
    });
    
    rep.on('message', function (msg) {
        console.log(`recieve: `, JSON.parse(msg));
        rep.send(JSON.stringify({ "status": FAIL, "code": 3666 }));
    });
    

    console

    recieve:  { method: 'login', login: 'a', password: 'b1' }
    accept, endpoint: tcp://0.0.0.0:5560
    accept, endpoint: tcp://0.0.0.0:5560
    login: a, password: b1
    recieve:  { method: 'login', login: 'a', password: 'b1' }
    disconnect, endpoint: tcp://0.0.0.0:5560
    login: a, password: b1
    disconnect, endpoint: tcp://0.0.0.0:5560
    

提交回复
热议问题