O'Reilly logo

ZeroMQ by Pieter Hintjens

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 to zmq_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 using memcpy(), and pass the message to zmq_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, use zmq_msg_size().

  • Do not use zmq_msg_move(), zmq_msg_copy(), or zmq_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 into ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required