If you recall from Chapter 2, Introduction to Sockets, we said that messages are prefix matched when using the publisher-subscriber pattern and we have showed a work-around to get what the subscriber really wants. This time, we visit the PUB-SUB sockets by enveloping messages with separate keys.
The following is the server code:
/* PUB – SUB wrap messages. server.c */ #include "czmq.h" int main (int argc, char const *argv[]) { zctx_t* context = zctx_new(); void* pub = zsocket_new(context, ZMQ_PUB); zsocket_bind(pub, "tcp://*:4040"); printf("starting server "); for(;;) { zstr_sendm(pub, "Company1"); zstr_send(pub, "Company Message to be ignored."); zstr_sendm(pub, "Company10"); zstr_send(pub, "Company message to receive."); zclock_sleep(10); } zsocket_destroy(context, pub); zctx_destroy(&context); return 0; }
And the following is the client code:
/* PUB – SUB envelop messages. client.c */ #include "czmq.h" int main (int argc, char const *argv[]) { zctx_t* context = zctx_new(); void* request = zsocket_new(context, ZMQ_SUB); printf("Starting client... "); zsocket_connect(request, "tcp://localhost:4040"); zsocket_set_subscribe (request, "Company10"); for(;;) { char* env = zstr_recv(request); char* msg = zstr_recv(request); printf("env: %s | %s ", env, msg); if(!msg) break; free(env); free(msg); zclock_sleep(1); } zsocket_destroy(context, request); zctx_destroy(&context); return 0; }
3.149.26.176