Pages

ØMQ publisher

After some general talking on the ØMQ publisher-subscriber pattern, let's see the gory details, writing a simple server that acts as a publisher, sending messages to anyone who is concerned.

Here is the C++ code that I have written, see below for a few comments:
try
{
zmq::context_t context(1); // 1
zmq::socket_t publisher(context, ZMQ_PUB); // 2
publisher.bind("tcp://*:5556"); // 3

std::stringstream ss;
std::string s;
for(int i = 0; i < 100; ++i)
{
readyToSend(); // 4

ss.str("");
ss << i%2 << ':' << i*42 << ':' << i; // 5.
s = ss.str();

zmq::message_t message((void *)s.c_str(), s.length(), NULL); // 6
std::cout << "Sending " << s << std::endl;
publisher.send(message); // 7
} // 8
} // 9
catch(const zmq::error_t& ze)
{
std::cout << "Exception: " << ze.what() << std::endl;
}

1. Through a context object we control the aquisition of the ØMQ resource, as the RAII idiom suggests. The class ctor calls the API function zmq_init().
2. Same RAII behaviour for socket_t, where its ctor call zmq_socket(). Here the socket type is ZMQ_PUB, since we want our application acting as a publisher in pub-sub context.
3. The socket bind function calls the ØMQ API function zmq_bind(), specifying here that we want to use the TCP protocol and the port on the host that we want to be grab.
4. A function that is going to determine when the application is ready to fire a new message.
5. Just put some silly data in the message. We assume a format X:Y:Z, three integers colon separated.
6. Let's create a message that uses as data the memory made available in the std::string s. The ctor used here calls the API function zmq_msg_init_data().
7. The message is sent through the socket - actually using zmq_send().
8. The message object goes out of scope, its dtor calls zmq_msg_close()
9. The socket goes out of scope, calling zmq_close(), ditto for the context - zmq_term().

The function called at [4] has the only aim of making testing easier. It just stops the application execution, asking the user a confirmation to continue:
void readyToSend()
{
std::cout << "Enter when ready" << std::endl;
std::string input;
std::getline(std::cin, input);
}

If you have found this post interesting, you are going to love the official Z-Guide.

No comments:

Post a Comment