nn_pubsub - Man Page
publish/subscribe scalability protocol
Synopsis
#include <nanomsg/nn.h>
#include <nanomsg/pubsub.h>
Description
Broadcasts messages to multiple destinations.
Messages are sent from NN_PUB sockets and will only be received by NN_SUB sockets that have subscribed to the matching topic. Topic is an arbitrary sequence of bytes at the beginning of the message body. The NN_SUB socket will determine whether a message should be delivered to the user by comparing the subscribed topics (using NN_SUB_SUBSCRIBE on a full SUB socket) to the bytes initial bytes in the incoming message, up to the size of the topic.
nn_setsockopt (s, NN_SUB, NN_SUB_SUBSCRIBE, "Hello", 5);
Will match any message with initial 5 bytes being "Hello", for example, message "Hello, World!" will match.
Topic with zero length matches any message.
If the socket is subscribed to multiple topics, message matching any of them will be delivered to the user.
Since the filtering is performed on the Subscriber side, all the messages from Publisher will be sent over the transport layer.
The entire message, including the topic, is delivered to the user.
Socket Types
- NN_PUB
This socket is used to distribute messages to multiple destinations. Receive operation is not defined.
- NN_SUB
Receives messages from the publisher. Only messages that the socket is subscribed to are received. When the socket is created there are no subscriptions and thus no messages will be received. Send operation is not defined on this socket.
Socket Options
- NN_SUB_SUBSCRIBE
Defined on full SUB socket. Subscribes for a particular topic. Type of the option is string. A single NN_SUB socket can handle multiple subscriptions.
- NN_SUB_UNSUBSCRIBE
Defined on full SUB socket. Unsubscribes from a particular topic. Type of the option is string.
Example
int pub = nn_socket (AF_SP, NN_PUB); int sub = nn_socket (AF_SP, NN_SUB); int nbytes; void *buf = NULL; char *addr = "inproc://example"; nn_setsockopt (sub, NN_SUB, NN_SUB_SUBSCRIBE, "foo", 3); nn_setsockopt (sub, NN_SUB, NN_SUB_SUBSCRIBE, "bar", 3); nn_bind(pub, addr); nn_connect(sub, addr); nbytes = nn_send (pub, "foo|Hello!", 10); assert(nbytes == 10); nbytes = nn_recv (sub, &buf, NN_MSG, 0); assert (nbytes == 10); nn_freemsg (buf); nbytes = nn_send (pub, "baz|World!", 10); /* Message is not delivered because if matches no subscription. */ nbytes = nn_recv(sub, &buf, NN_MSG, 0);
See Also
nn_bus(7) nn_reqrep(7) nn_pipeline(7) nn_survey(7) nn_pair(7) nanomsg(7)
Authors
Referenced By
nanomsg(7), nn_bus(7), nn_pair(7), nn_pipeline(7), nn_reqrep(7), nn_socket(3), nn_survey(7).