10
votes

Could anyone please provide a real-world example of using zmq with the router/dealer pattern, and explain its advantage over the more simple publish/subscribe pattern? Thanks.

2

2 Answers

13
votes

A 'real-world' example: Stock market simulation

Router socket is the server (or 'Market'), Dealer sockets are the clients (or 'Traders').

  1. Traders place buy and sell orders by sending relevant 'order' messages to the Market.
  2. The Market responds immediately with an 'acknowledge' message
  3. Sometime later when an order is fulfilled the Market sends 'order complete' messages to all involved traders.

This sort of behavior would be quite cumbersome to implement with pub/sub as you would need both Market and Traders to run a Publisher and a Subscriber socket to allow the 2 way communication. There would also be privacy concerns if all completed transactions were 'published' rather than sent direct to the relevant traders. (Trader B should not get to know that Trader A bought or sold something).

What makes Router sockets different

Sending and receiving from Router sockets are slightly more complicated to allow the asynchronous responses:

  1. Any incoming message has an identity frame prepended to the incoming message upon receipt, this indicates which client the message came from.
  2. The first frame of any sent message is removed and used to identify which client to send the response to.

The 'identity' is a string and will be set to something unique per connected client by default, but you can set custom identities on client sockets via socket options.

3
votes

Dealers send their client ID with each message. Router is able to accept connections from multiple dealers and each time a message is received, it is able to discern which client sent the message. It is also able to send messages to specific clients by referring to their IDs.

Real life example: game server lets clients join a room until it is full. It keeps track of each client ID in the room. When room is full, it loops over each client ID within that room and sends them a "game started" message.