ROUTER Broker and DEALER Workers

Anywhere you can use REQ, you can use DEALER. There are two specific differences:

  • The REQ socket always sends an empty delimiter frame before any data frames; the DEALER does not.

  • The REQ socket will send only one message before it receives a reply; the DEALER is fully asynchronous.

The synchronous versus asynchronous behavior has no effect on our example since we’re doing strict request-reply. It is more relevant when we come to recovering from failures, which we’ll address in Chapter 4.

Now let’s look at exactly the same example, but with the REQ socket replaced by a DEALER socket (Example 3-4).

Example 3-4. ROUTER-to-DEALER (rtdealer.c)

//
//  ROUTER-to-DEALER example
//
#include "zhelpers.h"
#include <pthread.h>

#define NBR_WORKERS 10

static void *
worker_task (void *args)
{
    void *context = zmq_ctx_new ();
    void *worker = zmq_socket (context, ZMQ_DEALER);
    s_set_id (worker);          //  Set a printable identity
    zmq_connect (worker, "tcp://localhost:5671");

    int total = 0;
    while (1) {
        //  Tell the broker we're ready for work
        s_sendmore (worker, "");
        s_send (worker, "Hi Boss");

        //  Get workload from broker, until finished
        free (s_recv (worker));     //  Envelope delimiter
        char *workload = s_recv (worker);
...

The code is almost identical, except that the worker uses a DEALER socket and reads and writes that empty frame before the data frame. This is the approach I use when I want to maintain compatibility with REQ workers.

However, remember the reason for that empty ...

Get ZeroMQ now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.