C

C

C 开发者有两种选择,CZMQ 或 libzmq,它是低层的 zeromq 库。

推荐给 C 开发者使用的是 CZMQ 绑定,它为 ØMQ 提供了高层 API,并提供了额外的类,例如 pollers、线程管理和安全助手。

CZMQ

Github https://github.com/zeromq/czmq
文档 http://czmq.zeromq.org/

安装

首先 安装 libzmq

Ubuntu/Debian/Mint

apt-get install libczmq-dev

Fedora

dnf install czmq-devel

OSX

brew install czmq

Windows

使用 vcpkg

.\vcpkg.exe install czmq

这将构建 czmq 作为 32 位共享库。

.\vcpkg.exe install czmq:x64-windows-static

这将构建 czmq 作为 64 位静态库。

要使用 draft API,你可以构建带有 draft 特性的 czmq

.\vcpkg install czmq[draft]

示例

#include <czmq.h>
int main (void)
{
    zsock_t *push = zsock_new_push ("inproc://example");
    zsock_t *pull = zsock_new_pull ("inproc://example");
    zstr_send (push, "Hello, World");

    char *string = zstr_recv (pull);
    puts (string);
    zstr_free (&string);

    zsock_destroy (&pull);
    zsock_destroy (&push);
    return 0;
}

libzmq

Github https://github.com/zeromq/libzmq
文档 https://libzmq.zeromq.cn/

安装

遵循 下载页面 上的说明。

示例

服务器

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

int main (void)
{
    //  Socket to talk to clients
    void *context = zmq_ctx_new ();
    void *responder = zmq_socket (context, ZMQ_REP);
    int rc = zmq_bind (responder, "tcp://*:5555");
    assert (rc == 0);

    while (1) {
        char buffer [10];
        zmq_recv (responder, buffer, 10, 0);
        printf ("Received Hello\n");
        sleep (1);          //  Do some 'work'
        zmq_send (responder, "World", 5, 0);
    }
    return 0;
}

客户端

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

int main (void)
{
    printf ("Connecting to hello world server…\n");
    void *context = zmq_ctx_new ();
    void *requester = zmq_socket (context, ZMQ_REQ);
    zmq_connect (requester, "tcp://localhost:5555");

    int request_nbr;
    for (request_nbr = 0; request_nbr != 10; request_nbr++) {
        char buffer [10];
        printf ("Sending Hello %d…\n", request_nbr);
        zmq_send (requester, "Hello", 5, 0);
        zmq_recv (requester, buffer, 10, 0);
        printf ("Received World %d\n", request_nbr);
    }
    zmq_close (requester);
    zmq_ctx_destroy (context);
    return 0;
}