nanomsg pub/sub with multiple subscribers using binary msg and topic name

419 Views Asked by At

how we can send msg from publisher to subscriber on different topics in one structure and how topics can be retrieved in subscriber.

  • C/C++ code example
1

There are 1 best solutions below

0
user3666197 On

Q : "how we can send msg from publisher to subscriber on different topics in one structure...?"

The pub-side can do just sending, like this :

#include <nanomsg/nn.h>
#include <nanomsg/pubsub.h>

...
int pub = nn_socket (AF_SP, NN_PUB);
assert (pub >= 0);
...

int nbytes;
char *addr = "inproc://example";

nn_bind(pub, addr);
...

nbytes = nn_send (pub, "a_Topic_#1abcdefghijklmnopqr", 28);
assert(nbytes == 28);

nbytes = nn_send (pub, "a_Topic_#2abcdefghijklmnopqr", 28);
assert(nbytes == 28);
...

nn_freemsg (buf);
...

Q : "... and how topics can be retrieved in subscriber?"

Using basically this mock-up principle, the sub-side has to subscribe first :

#include <nanomsg/nn.h>
#include <nanomsg/pubsub.h>

...
int sub = nn_socket (AF_SP, NN_SUB);
assert (sub >= 0);
...

int nbytes;
void *buf = NULL;
char *addr = "inproc://example";

nn_connect(sub, addr);
...

nn_setsockopt (sub, NN_SUB, NN_SUB_SUBSCRIBE, "a_Topic_#1", 10);
nn_setsockopt (sub, NN_SUB, NN_SUB_SUBSCRIBE, "a_Topic_#2", 10);
...

nbytes = nn_recv (sub, &buf, NN_MSG, 0);
assert (nbytes == 28);

nn_freemsg (buf);
...