Retrieving subscriber count using zeromq PUB/SUB sockets

后端 未结 3 2190
温柔的废话
温柔的废话 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:48

    There doesn't seem to be any direct way. Below is Python code to monitor socket events which can be used to maintain count:

    import zmq
    from zmq.eventloop import ioloop, zmqstream
    import zmq.utils.monitor
    
    class Publication:
        def start(self, port, host):
            context = zmq.Context()
            self._socket = context.socket(zmq.PUB)
            self._socket.bind("tcp://%s:%d" % (host, port))
            self._mon_socket = self._socket.get_monitor_socket(zmq.EVENT_CONNECTED | zmq.EVENT_DISCONNECTED)
            self._mon_stream = zmqstream.ZMQStream(self._mon_socket)
            self._mon_stream.on_recv(self._on_mon)
    
        def _on_mon(self, msg):
            ev = zmq.utils.monitor.parse_monitor_message(msg)
            event = ev['event']
            endpoint = ev['endpoint']
            if event == zmq.EVENT_CONNECTED:
                pass
                # print(endpoint)
            elif event == zmq.EVENT_DISCONNECTED:
                pass
                #print(endpoint)
    

    One issue is that for some reason CONNECTED event is not firing. Another issue is that even when event fires, you only get endpoint ID which is like tcp://ip:port string. So for multiple clients on same node you get same endpoint ID.

提交回复
热议问题