Working with Messages
On the wire, ÃMQ messages are blobs of any size, from zero upwards, that fit in memory. You do your own serialization using protobufs, msgpack, JSON, or whatever else your applications need to speak. Itâs wise to choose a data representation that is portable and fast, but you can make your own decisions about trade-offs.
In memory, ÃMQ messages are zmq_msg_t
structures (or classes, depending on
your language). Here are the basic ground rules for using ÃMQ messages
in C:
You create and pass around
zmq_msg_t
objects, not blocks of data.To read a message, you use
zmq_msg_init()
to create an empty message, and then you pass that tozmq_msg_recv()
.To write a message from new data, you use
zmq_msg_init_size()
to create a message and at the same time allocate a block of data of some size. You then fill that data usingmemcpy()
, and pass the message tozmq_msg_send()
.To release (not destroy) a message, you call
zmq_msg_close()
. This drops a reference, and eventually ÃMQ will destroy the message.To access the message content, you use
zmq_msg_data()
. To know how much data the message contains, usezmq_msg_size()
.Do not use
zmq_msg_move()
,zmq_msg_copy()
, orzmq_msg_init_data()
unless youâve read the manual pages and know precisely why you need these.
Here is a typical chunk of code working with messages that should be familiar if you have been paying attention. This is from the zhelpers.h file we use in all the examples:
// Receive 0MQ string from socket and convert ...
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.