zeromq pub/sub c 中的示例 (libzmq)

zeromq pub/sub example in c (libzmq)

有人可以用 libzmq 向我展示 zeromq pub/sub 的“Hello World”示例吗?我已经完成了 req/rep 示例的编码 它有据可查,但我找不到适合我的 pub/sub 的好 hello world 示例。 这是我的代码不起作用。

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;
}

提前致谢

我终于可以使用这段代码了

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;
}