Pub-Sub Message Envelopes

In the pub-sub pattern, we can split the key into a separate message frame that we call an envelope. If you want to use pub-sub envelopes, make them yourself. It’s optional, and in previous pub-sub examples, we didn’t do this. Using a pub-sub envelope is a little more work for simple cases, but it’s cleaner, especially for real cases, where the key and the data are naturally separate things.

Figure 2-15 shows is what a publish-subscribe message with an envelope looks like.

Pub-sub envelope with separate key

Figure 2-15. Pub-sub envelope with separate key

Recall that subscriptions do a prefix match. That is, they look for “all messages starting with XYZ.” The obvious question is: how to delimit keys from data so that the prefix match doesn’t accidentally match data. The best answer is to use an envelope, because the match won’t cross a frame boundary.

Here is a minimalist example of how pub-sub envelopes look in code. This publisher (Example 2-15) sends messages of two types, A and B. The envelope holds the message type.

Example 2-15. Pub-sub envelope publisher (psenvpub.c)

//
//  Pub-sub envelope publisher
//  Note that the zhelpers.h file also provides s_sendmore
//
#include "zhelpers.h"

int main (void)
{
    //  Prepare our context and publisher
    void *context = zmq_ctx_new ();
    void *publisher = zmq_socket (context, ZMQ_PUB);
    zmq_bind (publisher, "tcp://*:5563");

    while (1) {
        // Write ...

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.