Book Image

ZeroMQ

By : Faruk Akgul
Book Image

ZeroMQ

By: Faruk Akgul

Overview of this book

<p>ØMQ (also spelled ZeroMQ, 0MQ, or ZMQ) is a high-performance asynchronous messaging library aimed at use in scalable distributed or concurrent applications. It provides a message queue, but unlike message-oriented middleware, a ØMQ system can run without a dedicated message broker. The library is designed to have a familiar socket-style API.<br /><br />"ZeroMQ" teaches you to use ZeroMQ through examples in C programming language. You will learn how to use fundamental patterns of message/queuing with a step-by-step tutorial approach and how to apply them. Then, you’ll learn how to use high level APIs and to work with multiple sockets and multithreaded programs through many examples.<br /><br />This book looks at how message/queue works in general and what kinds of problems it solves. Then, it explains how ZeroMQ works and how it differs from other message/queue libraries and how it can be used in different scenarios.<br /><br />You will also learn how to apply essential message/queue design patterns in different scenarios, and how they differ from each other. It shows you practical examples you can apply. You will also learn how to work with multiple sockets.<br /><br />You will learn the basics of ZeroMQ as well as how to use different patterns.</p>
Table of Contents (12 chapters)

Working with multiple sockets


In Chapter 1, Getting Started, and Chapter 2, Introduction to Sockets, we worked on programs with a single socket. Working on one socket is easy, but working on multiple sockets is somewhat tricky. To work with multiple sockets, we use zmq_poll(3), which is an event loop that allows an application to multiplex I/O with multiple sockets.

/*
  
  Polling with ZeroMQ

*/
#include <string.h>
#include "zmq.h"

int main (int argc, char const *argv[]) {
  
  void* ctx = zmq_ctx_new();
  void* pull = zmq_socket(ctx, ZMQ_PULL);
  zmq_connect(pull, "tcp://localhost:4040");
  
  void* subscriber = zmq_socket(ctx, ZMQ_SUB);

  char* company_name = "Company1";
  int length = strlen(company_name) + 1;

  zmq_connect(subscriber, "tcp://localhost:5050");
  zmq_setsockopt(subscriber, ZMQ_SUBSCRIBE, company_name, length);
  
  printf("starting...\n");
  
  zmq_pollitem_t polls[2];
  
  polls[0].socket = pull;
  polls[0].fd = 0;
  polls[0].events = ZMQ_POLLIN;
  polls[0]...