A High-Level API for ÃMQ
Weâre going to push request-reply onto the stack now and open a different area, which is the ÃMQ API itself. Thereâs a reason for this detour: as we write more complex examples, the low-level ÃMQ API starts to look increasingly clumsy. Look at the core of the worker thread from our load-balancing broker:
while
(
true
)
{
// Read and save all frames until we get an empty frame
// In this example there is only 1 but there could be more
char
*
address
=
s_recv
(
worker
);
char
*
empty
=
s_recv
(
worker
);
assert
(
*
empty
==
0
);
free
(
empty
);
// Get request, send reply
char
*
request
=
s_recv
(
worker
);
printf
(
"Worker: %s
\n
"
,
request
);
free
(
request
);
s_sendmore
(
worker
,
address
);
s_sendmore
(
worker
,
""
);
s_send
(
worker
,
"OK"
);
free
(
address
);
}
That code isnât even reusable because it can only handle one reply
address in the envelope, and it already does some wrapping around the ÃMQ
API. If we used the libzmq
API directly, this is what
weâd have to write:
while
(
true
)
{
// Read and save all frames until we get an empty frame
// In this example there is only 1 but there could be more
zmq_msg_t
address
;
zmq_msg_init
(
&
address
);
zmq_msg_recv
(
worker
,
&
address
,
0
);
zmq_msg_t
empty
;
zmq_msg_init
(
&
empty
);
zmq_msg_recv
(
worker
,
&
empty
,
0
);
// Get request, send reply
zmq_msg_t
payload
;
zmq_msg_init
(
&
payload
);
zmq_msg_recv
(
worker
,
&
payload
,
0
);
int
char_nbr
;
printf
(
"Worker: "
);
for
(
char_nbr
=
0
;
char_nbr
<
zmq_msg_size
(
&
payload
);
char_nbr
++
)
printf
(
"%c"
,
*
(
char ...
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.