Publish/Subscribe API for Windows C++ SDK (legacy)

New SDK available

The Windows C++ SDK is built on C-Core (legacy), which is still supported. If you are starting a new project, use the new C SDK.

Publish​

The publish() function is used to send a message to all subscribers of a channel. To publish a message you must first specify a valid publish_key at initialization. A successfully published message is replicated across the PubNub Real-Time Network and sent simultaneously to all subscribed clients on a channel.

Messages in transit can be secured from potential eavesdroppers with SSL/TLS by setting ssl to true during initialization.

Publish anytime​

It's not required to be subscribed to a channel in order to publish to that channel.

Message data​

The message argument can contain any JSON serializable data, including: Objects, Arrays, Ints and Strings. data should not contain special Windows C++ classes or functions as these will not serialize. String content can include any single-byte or multi-byte UTF-8 character.

JSON serialize

JSON serialize! It is important to note that you should JSON serialize when sending signals/messages via PUBNUB.

Message size​

The maximum number of characters per message is 32 KiB by default. The maximum message size is based on the final escaped character count, including the channel name. An ideal message size is under 1800 bytes which allows a message to be compressed and sent using single IP datagram (1.5 KiB) providing optimal network performance.

If the message you publish exceeds the configured size, you will receive the following message:

Message too large error​

1["PUBLISHED",[0,"Message Too Large","13524237335750949"]]

For further details please check: https://support.pubnub.com/hc/en-us/articles/360051495932-Calculating-Message-Payload-Size-Before-Publish

Need larger messages?

PubNub supports payloads larger than the standard limit, but raising it requires verifying compatibility with your use case.

Talk to our team to discuss increasing the message size limit for your use case.

Message publish rate​

Messages can be published as fast as bandwidth conditions will allow. There is a soft limit based on max throughput since messages will be discarded if the subscriber can't keep pace with the publisher.

For example, if 200 messages are published simultaneously before a subscriber has had a chance to receive any messages, the subscriber may not receive the first 100 messages because the message queue has a limit of only 100 messages stored in memory.

Publishing to multiple channels​

It is not possible to publish a message to multiple channels simultaneously. The message must be published to one channel at a time.

Publishing messages reliably​

There are some best practices to ensure messages are delivered when publishing to a channel:

  • Publish to any given channel in a serial manner (not concurrently).
  • Check that the return code is success (e.g. [1,"Sent","136074940..."])
  • Publish the next message only after receiving a success return code.
  • If a failure code is returned ([0,"blah","<timetoken>"]), retry the publish.
  • Avoid exceeding the in-memory queue's capacity of 100 messages. An overflow situation (aka missed messages) can occur if slow subscribers fail to keep up with the publish pace in a given period of time.
  • Throttle publish bursts in accordance with your app's latency needs e.g. Publish no faster than 5 msgs per second to any one channel.

Method(s)​

To Publish a message you can use the following method(s) in the Windows C++ SDK:

1publish (std::string const &channel, std::string const &message)
* required
ParameterDescription
channel *
Type: std::string const &
Specifies channel ID to publish messages to.
message *
Type: std::string const &
The message.
1publishv2 (std::string const &channel, std::string const &message, pubv2_opt options)
* required
ParameterDescription
channel *
Type: std::string const &
Specifies channel ID to publish messages to.
message *
Type: std::string const &
The message to publish.
options *
Type: pubnub::pubv2_opt
Options for Publish v2. These are designed to be used as bit-masks, for which purpose there are overloaded & and `

Sample code​

Publish a message to a channel​

1// Sync
2void publish(pubnub::context &pn) {
3 enum pubnub_res res;
4
5 res = pn.publish("my_channel", "\"Hello from the PubNub C++ SDK!\"").await();
6
7 if (PNR_OK == res) {
8 std::cout << pn.last_publish_result() << std::endl;
9 } else {
10 std::cout << "Publish request failed" << std::endl;
11 }
12}
13
14// Lambdas
15void publish(pubnub::context &pn) {
show all 37 lines
Subscribe to the channel

Before running the above publish example, either using the Debug Console or in a separate script running in a separate terminal window, subscribe to the same channel that is being published to.

Rest response from server​

The function returns the following formatted response:

1[1, "Sent", "13769558699541401"]

Other examples​

Publish a JSON serialized message​

1// Sync
2void publish(pubnub::context &pn) {
3 enum pubnub_res res;
4
5 res = pn.publish("my_channel", "{\"msg\": \"Hello from the PubNub C++ SDK!\"}").await();
6
7 if (PNR_OK == res) {
8 std::cout << pn.last_publish_result() << std::endl;
9 } else {
10 std::cout << "Publish request failed" << std::endl;
11 }
12}
13
14// Lambdas
15void publish(pubnub::context &pn) {
show all 37 lines

Publish with cipher key​

1res = pubnub_publish_encrypted(pbp, chan, "\"Hello world from crypto sync!\"", cipher_key);
2if (res != PNR_STARTED) {
3 printf("pubnub_publish() returned unexpected: %d\n", res);
4 pubnub_free(pbp);
5 return -1;
6}

Publish with cipher key using pubnub_publish_ex​

Using this method you can reuse the cipherKey from the options.

1struct pubnub_publish_options opt = pubnub_publish_defopts();
2opt.cipher_key = my_cipher_key;
3pbresult = pubnub_publish_ex(pn, "my_channel", "42", opt);

Signal​

Sends a signal @p message on the @p channel via chosen @p method (GET by default).

By default, signals are limited to a message payload size of 64 bytes. This limit applies only to the payload, and not to the URI or headers. If you require a larger payload size, please contact support.

Method(s)​

Declaration​

futres signal(std::string const& channel, std::string const& message)

Parameters​

* required
ParameterDescription
channel *
Type: std::string
Channel ID to send a signal to.
message *
Type: std::string
Message to send (signal), in JSON format.

Sample code​

Signal a message to a channel​

1futres fr = pb.signal("my_channel", "\"singalling\"");

Returns​

TypeValueDescription
pubnub::futresUse to get the outcome of the transaction, in the same way as all other transactions

Subscribe​

This function causes the client to create an open TCP socket to the PubNub Real-Time Network and begin listening for messages on a specified channel ID. To subscribe to a channel ID the client must send the appropriate subscribe_key at initialization. By default a newly subscribed client will only receive messages published to the channel after the subscribe() call completes.

Context usage

Typically, you will want two separate contexts for publish and subscribe anyway. If you are changing the set of channels you subscribe to, you should first call leave() on the old set.

The subscribe() interface is essentially a transaction to start listening on the channel for arrival of next message. This has to be followed by a call to the method get() or get_all( ) to retrieve the actual message, once the subscribe transaction completes successfully. This needs to be performed every time it is desired to retrieve a message from the channel.

Unsubscribing from all channels

Unsubscribing from all channels, and then subscribing to a new channel Y is not the same as subscribing to channel Y and then unsubscribing from the previously-subscribed channel(s). Unsubscribing from all channels resets the last-received timetoken and thus, there could be some gaps in the subscription that may lead to message loss.

Method(s)​

To Subscribe to a channel you can use the following method(s) in the Windows C++ SDK:

1subscribe (std::string const &channel, std::string const &channel_group="")
* required
ParameterDescription
channels *
Type: std::string const &
Specifies the channel ID to which to subscribe
channel_group *
Type: std::string const &
Specifies channel_group to which to subscribe
1subscribe (std::vector<std::string> const &channel, std::vector< std::string > const &channel_group)
* required
ParameterDescription
channel *
Type: std::vector<std::string> const &
Specifies channel(s) to which to subscribe
channel_group *
Type: std::vector<std::string> const &
Specifies channel_groups to which to subscribe

Sample code​

Subscribe to a channel:

1// Sync
2void subscribe(pubnub::context &pn) {
3 enum pubnub_res res;
4
5 for (;;) {
6 res = pn.subscribe("my_channel").await();
7
8 if (PNR_OK == res) {
9 std::vector<std::string> msg = pn.get_all();
10
11 for (std::vector<std::string>::iterator it = msg.begin(); it != msg.end(); ++it) {
12 std::cout << *it << std::endl;
13 }
14 } else {
15 std::cout << "Request failed" << std::endl;
show all 52 lines

Rest response from server​

The output below demonstrates the response format to a successful call:

1[[], "Time Token"]

Other examples​

Subscribing to multiple channels​

It's possible to subscribe to more than one channel using the Multiplexing feature. The example shows how to do that using an array to specify the channel names.

Alternative subscription methods

You can also use Wildcard Subscribe and Channel Groups to subscribe to multiple channels at a time. To use these features, the Stream Controller add-on must be enabled on your keyset in the Admin Portal.

1//Sync
2enum pubnub_res res;
3res = pn.subscribe("my_channel1,my_channel2").await();
4
5//Lambdas
6enum pubnub_res res;
7pn.subscribe("my_channel1,my_channel2").then(...);
8
9//Functions
10enum pubnub_res res;
11pn.subscribe("my_channel1,my_channel2").then(on_connect);

Subscribing to a Presence channel​

Requires Presence

This method requires that the Presence add-on is enabled for your key in the Admin Portal.

For information on how to receive presence events and what those events are, refer to Presence Events.

For any given channel there is an associated Presence channel. You can subscribe directly to the channel by appending -pnpres to the channel name. For example the channel named my_channel would have the presence channel named my_channel-pnpres.

1// Sync
2void presence(pubnub::context &pn) {
3 enum pubnub_res res;
4 bool done = false;
5
6 while (!done) {
7 res = pn.subscribe("my_channel-pnpres").await();
8
9 if (PNR_OK == res) {
10 std::vector<std::string> msg = pn.get_all();
11
12 for (std::vector<std::string>::iterator it = msg.begin(); it != msg.end(); ++it) {
13 std::cout << *it << std::endl;
14 }
15
show all 70 lines

Sample Responses​

Join event​

1{
2 "action": "join",
3 "timestamp": 1345546797,
4 "uuid": "175c2c67-b2a9-470d-8f4b-1db94f90e39e",
5 "occupancy": 2
6}

Leave event​

1{
2 "action" : "leave",
3 "timestamp" : 1345549797,
4 "uuid" : "175c2c67-b2a9-470d-8f4b-1db94f90e39e",
5 "occupancy" : 1
6}

Timeout event​

1{
2 "action": "timeout",
3 "timestamp": 1345549797,
4 "uuid": "76c2c571-9a2b-d074-b4f8-e93e09f49bd",
5 "occupancy": 0
6}

State change event​

1{
2 "action": "state-change",
3 "uuid": "76c2c571-9a2b-d074-b4f8-e93e09f49bd",
4 "timestamp": 1345549797,
5 "data": {
6 "isTyping": true
7 }
8}

Interval event​

1{
2 "action":"interval",
3 "timestamp":1474396578,
4 "occupancy":2
5}

When a channel is in interval mode with presence_deltas pnconfig flag enabled, the interval message may also include the following fields which contain an array of changed UUIDs since the last interval message.

  • joined
  • left
  • timedout

For example, this interval message indicates there were 2 new UUIDs that joined and 1 timed out UUID since the last interval:

1{
2 "action" : "interval",
3 "occupancy" : <# users in channel>,
4 "timestamp" : <unix timestamp>,
5 "joined" : ["uuid2", "uuid3"],
6 "timedout" : ["uuid1"]
7}

If the full interval message is greater than 30 KB (since the max publish payload is ∼32 KiB), none of the extra fields will be present. Instead there will be a here_now_refresh boolean field set to true. This indicates to the user that they should do a hereNow request to get the complete list of users present in the channel.

1{
2 "action" : "interval",
3 "occupancy" : <# users in channel>,
4 "timestamp" : <unix timestamp>,
5 "here_now_refresh" : true
6}

Subscribe to a channel group​

Requires Stream Controller add-on

This method requires that the Stream Controller add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.

1//Sync
2static void subscribe_to_group(pubnub::context &pn) {
3 enum pubnub_res res;
4
5 for (;;) {
6 try {
7 res = pn.subscribe("", channel_group).await();
8
9 if (PNR_OK == res) {
10 std::vector<std::string> msg = pn.get_all();
11
12 for (std::vector<std::string>::iterator it = msg.begin(); it != msg.end(); ++it) {
13 std::cout << *it << std::endl;
14 }
15
show all 77 lines

Subscribe to the Presence channel of a channel group​

Requires Stream Controller and Presence add-ons

This method requires both the Stream Controller and Presence add-ons are enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.

1//Sync
2static void presence_of_group(pubnub::context &pn) {
3 enum pubnub_res res;
4
5 for (;;) {
6 try {
7 res = pn.subscribe("", channel_group + "-pnpres").await();
8
9 if (PNR_OK == res) {
10 std::vector<std::string> msg = pn.get_all();
11
12 for (std::vector<std::string>::iterator it = msg.begin(); it != msg.end(); ++it) {
13 std::cout << *it << std::endl;
14 }
15
show all 77 lines

Using cipherKey with subscribe​

For subscribe, you don't use the cipher key at subscribe, but, when you get the received messages after the subscribe transaction has finished:

1char msg[MAX_MSG_LEN];
2pbresult = pubnub_get_decrypted(pn, my_cipher_key, s, sizeof s);
3if (PNR_OK == pbresult) {
4 /* Use the message in `msg` */
5}

or, for a different usability/safety trade-off:

1pubnub_bymebl_t msg = pubnub_get_decrypted_alloc(pn, my_cipher_key);
2if (msg.ptr != NULL) {
3 /* use the message in `msg.ptr` */
4 free(msg.ptr);
5}

Subscribe v2​

Subscribe v2 options structure​

Starts a subscribe V2 transaction on the channel (or channels) @p channel, with options @p opt.

Method(s)​

Declaration​

futres subscribe_v2(std::string const& channel, subscribe_v2_options opt); futres subscribe_v2(std::vector<std::string> const& channels, subscribe_v2_options opt);

Members​

* required
ParameterDescription
channel *
Type: std::string
Channel ID to start a subscribe V2 on.
channels *
Type: std::vector<std::string>
Vector of channels to start a subscribe V2 on.
opt *
Type: subscribe_v2_options
Options of the subscribe V2 to start (channel group, heartbeat, filter...).

Sample code​

1futres fr = pb.subscribe_v2("my_channel", subscribe_v2_options());

Subscribe to a channel group example​

1futres fr = pb.subscribe_v2("", subscribe_v2_options().channel_group("my_group"));

Returns​

TypeValueDescription
pubnub::futresUsed to get the outcome of the transaction, like for any other transaction.

Get V2 message​

Returns the next v2 message from the context. If there are none left, returns an empty message structure (checked through v2_mesage::is_empty())

Method(s)​

Declaration​

v2_message get_v2() const;

Parameter​

none

Sample code​

1auto v2_msg = pb.get_v2();
2 if (v2_msg.is_empty()) {
3 std::cout << "No more messages in the context\n";
4 }
5 else {
6 std::cout << "Received message on channel:" << v2_msg.channel()
7 << "\n match (or group): " << v2_msg.match_or_group()
8 << "\n payload: " << v2_msg.payload() << "\n";
9}

Get all V2 messages​

Returns a vector of all v2 messages from the context. If none are left, returned vector will be empty.

Method(s)​

Declaration​

std::vector<v2_message> get_all_v2() const;

Parameter​

none

Sample code​

1for (auto v2_msg: pb.get_all_v2()) {
2 std::cout << "Received message on channel:" << v2_msg.channel()
3 << "\n match (or group): " << v2_msg.match_or_group()
4 << "\n payload: " << v2_msg.payload() << "\n";
5}

Subscribe V2 options class​

A wrapper class for subscribe_v2 options structure, enabling a nicer usage. Something like:

Method(s)​

Declaration​

pn.subscribe(chan, subscribe_v2_options().heartbeat(412));

Parameter​

MemberParameterReturnDescription
Default constructorInitializes options to their defaults
channel_or_groupstd::string const& chgroup*thisSets channel group option. It's copied into this object, so the user need not keep chgroup alive any further more.
std::vector<std::string> const& chgroup*thisHelper method to set channel group via a vector of channel groups
heartbeatunsigned hb_interval*thisSets the heartbeat interval
filter_exprstd::string const* filter_expr*thisSets the filter expression to use (expression is Javascript-like). It's copied into this object, so the user need not keep filter_expr alive any further more
data(none)pubnub_subscribe_v2_optionsReturns the value of the wrapped subscribe v2 options structure

Message V2 class​

A wrapper class for pubnub_v2_message structure, enabling a nicer usage, creating std::strings from character buffers and providing some helper functions, such as is_empty().

MemberParameterReturnDescription
Default constructorInitializes all message elements to zeroes (empty).
constructorpubnub_v2_message message_v2*thisInitializes the wrapped message to the given message_v2
tt(none)std::stringThe timetoken of the message
region(none)intThe region of the message
flags(none)intThe flags of the message
channel(none)std::stringThe matched channel ID or group
payload(none)std::stringThe payload of the message
metadata(none)pubnub_message_typeThe type of the message (published, signal)
is_empty(none)boolReturns whether the message is empty (there is no message actually, this object is a placeholder). Message is considered empty if there is no timetoken info(whose existence is obligatory for any valid v2 message). This does not mean that the payload of the message is empty, as it cannot be, it has to be in JSON format.

Unsubscribe​

To unsubscribe, you need to cancel a subscribe transaction.

  • If you configured SDK to be thread-safe, you can cancel at any time, but, the cancelling may actually fail - i.e., your thread may wait for another thread to finish working with the context, and by the time your cancel request gets processed, the transaction may finish.
  • If you configured SDK to not be thread-safe, the only safe way to do it is to use the sync interface and:
  1. Set the context to use non-blocking I/O.
  2. Wait for the outcome in a loop, checking for pubnub_last_result() - rather than calling pubnub_await().
  3. If a condition occurs that prompts you to unsubscribe, call cancel().
  4. Wait for the cancellation to finish (here you can call pubnub_await(), unless you want to do other stuff while you wait).
Unsubscribing from all channels

Unsubscribing from all channels, and then subscribing to a new channel Y is not the same as subscribing to channel Y and then unsubscribing from the previously-subscribed channel(s). Unsubscribing from all channels resets the last-received timetoken and thus, there could be some gaps in the subscription that may lead to message loss.

Method(s)​

To Unsubscribe from a channel you can use the following method(s) in the Windows C++ SDK:

  1. Go to PubNub Leave Method.

Sample code​

Unsubscribe from a channel:

1auto futr = ctx.subscribe( "my_channel");
2/* If we don't set non-blocking I/O, we can't get out of a blocked read */
3ctx.set_blocking_io(pubnub::blocking);
4/* Can't use await() here, it will block */
5auto pbresult = PNR_STARTED;
6while (PNR_STARTED == pbresult) {
7 pbresult = futr.last_result();
8 /* Somehow decide we want to quit / unsubscribe */
9 if (should_stop()) {
10 ctx.cancel();
11 /* If we don't have anything else to do, it's OK to await now,
12 * but you could again have a loop "against" pubnub_last_result()
13 */
14 pbresult = futr.await();
15 break;
show all 20 lines

Rest response from server​

The output below demonstrates the response to a successful call:

1{
2 "action" : "leave"
3}

Was this page useful?

Last updated on