What is zmq.ROUTER and zmq.DEALER in python zeromq?

user27 picture user27 · May 10, 2014 · Viewed 11.6k times · Source

Can anyone tell what are the types of zmq.sockets?

In what situation one can use these sockets?

The main difference I need is zmq.DEALER and zmq.ROUTER in python zeroMQ?

Which type of socket can use these sockets?

Answer

Jan Vlcinsky picture Jan Vlcinsky · May 11, 2014

DEALER and ROUTER are sockets, which can allow easy scaling of REQ / REP pairs.

In direct communication, REQ and REP are talking in blocking manner.

ROUTER - accept requests - from REQ side

A router is able to accepts requests, adds an envelope with information about that requestee, and makes this new message available for further processing by interconnecting code). When the response comes back (in an envelop), it can pass the response back to the requestee.

DEALER - talks to workers - on REP side

Dealer cares about workers. Note, that to make the whole solution usable, workers have to connect to the dealer, not the other way around.

DEALER also allows non-blocking connection with REP.

Some connecting code passes a request in an envelope to the DEALER. The dealer manages the distribution of such requests to workers (without the envelope) and later responds back to the interconnecting code (again in an envelope).

Interconnecting code

An interconnecting code is to shuffle messages between ROUTER and DEALER sockets.

The simplest version is here: http://zguide.zeromq.org/py:rrbroker

# Simple request-reply broker
#
# Author: Lev Givon <lev(at)columbia(dot)edu>

import zmq

# Prepare our context and sockets
context = zmq.Context()
frontend = context.socket(zmq.ROUTER)
backend = context.socket(zmq.DEALER)
frontend.bind("tcp://*:5559")
backend.bind("tcp://*:5560")

# Initialize poll set
poller = zmq.Poller()
poller.register(frontend, zmq.POLLIN)
poller.register(backend, zmq.POLLIN)

# Switch messages between sockets
while True:
  socks = dict(poller.poll())

  if socks.get(frontend) == zmq.POLLIN:
    message = frontend.recv_multipart()
    backend.send_multipart(message)

  if socks.get(backend) == zmq.POLLIN:
    message = backend.recv_multipart()
    frontend.send_multipart(message)