The CZMQ High-Level API
Turning this wish list into reality for the C language gives us CZMQ, a ÃMQ language binding for C. This high-level binding, in fact, was developed out of earlier versions of this book. It combines nicer semantics for working with ÃMQ with some portability layers, and (importantly for C, but less for other languages) containers like hashes and lists. CZMQ also uses an elegant object model that leads to frankly lovely code.
Example 3-10 shows the load-balancing broker rewritten to use a higher-level API (CZMQ for the C case).
Example 3-10. Load-balancing broker using high-level API (lbbroker2.c)
//
// Load-balancing broker
// Demonstrates use of the CZMQ API
//
#include "czmq.h"
#define NBR_CLIENTS 10
#define NBR_WORKERS 3
#define WORKER_READY "\001"
// Signals worker is ready
// Basic request-reply client using REQ socket
//
static
void
*
client_task
(
void
*
args
)
{
zctx_t
*
ctx
=
zctx_new
();
void
*
client
=
zsocket_new
(
ctx
,
ZMQ_REQ
);
zsocket_connect
(
client
,
"ipc://frontend.ipc"
);
// Send request, get reply
while
(
true
)
{
zstr_send
(
client
,
"HELLO"
);
char
*
reply
=
zstr_recv
(
client
);
if
(
!
reply
)
break
;
printf
(
"Client: %s
\n
"
,
reply
);
free
(
reply
);
sleep
(
1
);
}
zctx_destroy
(
&
ctx
);
return
NULL
;
}
// Worker using REQ socket to do load balancing
//
static
void
*
worker_task
(
void
*
args
)
{
zctx_t
*
ctx
=
zctx_new
();
void
*
worker
=
zsocket_new
(
ctx
,
ZMQ_REQ
);
zsocket_connect
(
worker
,
"ipc://backend.ipc"
);
// Tell broker we're ready for work
zframe_t
*
frame
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.