March 2013
Intermediate to advanced
516 pages
15h 11m
English
The second classic pattern is one-way data distribution, in which a server pushes updates to a set of clients. Let’s look at an example that pushes out weather updates consisting of a zip code, temperature, and relative humidity. We’ll generate random values, just like the real weather stations do.
Example 1-6 shows the code for the server. We’ll use port 5556 for this application.
Example 1-6. Weather update server (wuserver.c)
//// Weather update server// Binds PUB socket to tcp://*:5556// Publishes random weather updates//#include "zhelpers.h"intmain(void){// Prepare our context and publishervoid*context=zmq_ctx_new();void*publisher=zmq_socket(context,ZMQ_PUB);intrc=zmq_bind(publisher,"tcp://*:5556");assert(rc==0);rc=zmq_bind(publisher,"ipc://weather.ipc");assert(rc==0);// Initialize random number generatorsrandom((unsigned)time(NULL));while(1){// Get values that will fool the bossintzipcode,temperature,relhumidity;zipcode=randof(100000);temperature=randof(215)-80;relhumidity=randof(50)+10;// Send message to all subscriberscharupdate[20];sprintf(update,"%05d %d %d",zipcode,temperature,relhumidity);s_send(publisher,update);}zmq_close(publisher);zmq_ctx_destroy(context);return0;}
There’s no start and no end to this stream of updates; it’s like a never-ending broadcast (Figure 1-4).
Figure 1-4. Publish-subscribe
Example 1-7 shows the client application, which listens to the ...
Read now
Unlock full access