Search code examples
czeromqpublish-subscribe

zeromq pub/sub example in c (libzmq)


Can someone show me "Hello World" example for zeromq pub/sub in c using libzmq. I have done coding req/rep example It's well documented but I couldn't find good hello world example for pub/sub that works fine with me. Here is my try.

pub.c

#include <zmq.h>
#include <string.h>

int main()
{
    void *context = zmq_ctx_new();
    void *publisher = zmq_socket(context, ZMQ_PUB);
    zmq_bind(publisher, "tcp://127.0.0.1:5555");

    char message[15] = "Hello World!";

    while(1)
    {
        zmq_msg_t msg;
        zmq_msg_init_size(&message, strlen(message));
        memcpy(zmq_msg_data(&msg), message, strlen(message));
        zmq_msg_send(publisher, &msg, 0);
        zmq_msg_close(&msg);
    }

    zmq_close(publisher);
    zmq_ctx_destroy(context);

    return 0;
}

sub.c

#include <zmq.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>

int main()
{
    void *context = zmq_ctx_new();
    void *subscriber = zmq_socket(context, ZMQ_SUB);
    int rc = zmq_connect(subscriber, "tcp://127.0.0.1:5555");
    assert(rc == 0);
    zmq_setsockopt(subscriber, ZMQ_SUBSCRIBE, "", 0);

    char message[15] = "";

    while(1)
    {
        zmq_msg_t msg;
        zmq_msg_init(&msg);
        zmq_msg_recv(subscriber, &msg, 0);
        int size = zmq_msg_size(&msg);
        memcpy(message, zmq_msg_data(&msg), size);
        zmq_msg_close(&msg);
        printf("%s\n", message);
    }

    zmq_close(subscriber);
    zmq_ctx_destroy(context);

    return 0;
}

Thanks in advance


Solution

  • Finally this code works with me

    pub.c

    #include <stdio.h>
    #include <assert.h>
    
    #include <zmq.h>
    
    int main()
    {
        void *context = zmq_ctx_new();
        void *publisher = zmq_socket(context, ZMQ_PUB);
        int rc = zmq_bind(publisher, "tcp://127.0.0.1:5556");
        assert(rc == 0);
    
        while(1)
        {
            rc = zmq_send(publisher, "Hello World!", 12, 0);
            assert(rc == 12);
        }
    
        zmq_close(publisher);
        zmq_ctx_destroy(context);
    
        return 0;
    }
    

    sub.c

    #include <stdio.h>
    #include <assert.h>
    
    #include <zmq.h>
    
    int main()
    {
        void *context = zmq_ctx_new();
        void *subscriber = zmq_socket(context, ZMQ_SUB);
        int rc = zmq_connect(subscriber, "tcp://127.0.0.1:5556");
        assert(rc == 0);
        rc = zmq_setsockopt(subscriber, ZMQ_SUBSCRIBE, "", 0);
        assert(rc == 0);
    
        char message[12];
    
        while(1)
        {
            rc = zmq_recv(subscriber, message, 12, 0);
            assert(rc != -1);
            printf("%s\n", message);
        }
    
        zmq_close(subscriber);
        zmq_ctx_destroy(context);
    
        return 0;
    }