Zizheng Tai
Zizheng Tai

Reputation: 6616

ZeroMQ: Many-to-one no-reply aynsc messages

I have read through the zguide but haven't found the kind of pattern I'm looking for:

  1. There is one central server (with known endpoint) and many clients (which may come and go).
  2. Clients keep sending hearbeats to the server, but they don't want the server to reply.
  3. Server receives heartbeats, but it does not reply to clients.
  4. Hearbeats sent when clients and server are disconnected should somehow be dropped to prevent a heartbeat flood when they go back online.

The closet I can think of is the DEALER-ROUTER pattern, but since this is meant to be used as an async REQ-REP pattern (no?), I'm not sure what would happen if the server just keep silent on incoming "requests." Also, the DEALER socket would block rather then start dropping heartbeats when the send High Water Mark is reached, which would still result in a heartbeat flood.

Upvotes: 3

Views: 2151

Answers (1)

Freek Wiekmeijer
Freek Wiekmeijer

Reputation: 4940

The PUSH/PULL pattern should give you what you need.

# Client example
import zmq

class Client(object):
    def __init__(self, client_id):
        self.client_id = client_id
        ctx = zmq.Context.instance()
        self.socket = ctx.socket(zmq.PUSH)
        self.socket.connect("tcp://localhost:12345")

    def send_heartbeat(self):
        self.socket.send(str(self.client_id))


# Server example
import zmq

class Server(object):
    def __init__(self):
        ctx = zmq.Context.instance()
        self.socket = ctx.socket(zmq.PULL)
        self.socket.bind("tcp://*:12345")  # close quote

    def receive_heartbeat(self):
        return self.socket.recv() # returns the client_id of the message's sender

This PUSH/PULL pattern works with multiple clients as you wish. The server should keep an administration of the received messages (i.e. a dictionary like {client_id : last_received} which is updated with datetime.utcnow() on each received message. And implement some housekeeping function to periodically check the administration for clients with old timestamps.

Upvotes: 3

Related Questions