Publish/Subscribe API for PubNub C-Core SDK
The foundation of the PubNub service is the ability to send a message and have it delivered anywhere in less than 100ms. Send a message to just one other person, or broadcast to thousands of subscribers at once.
For higher-level conceptual details on publishing and subscribing, refer to Connection Management and to Publish Messages.
Publish
The pubnub_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.
- Prerequisites and limitations
- Security
- Message data
- Size
- Publish rate
- Best practices
- You must initialize PubNub with the
publishKey
. - You don't have to be subscribed to a channel to publish to it.
- You cannot publish to multiple channels simultaneously.
You can secure the messages with SSL/TLS by setting ssl
to true
during initialization. You can also encrypt messages.
The message can contain any JSON-serializable data (Objects, Arrays, Ints, Strings) and shouldn't contain any special classes or functions. String content can include any single-byte or multi-byte UTF-8 characters.
Don't JSON serialize
You should not JSON serialize the message
and meta
parameters when sending signals, messages, or files as the serialization is automatic. Pass the full object as the message/meta payload and let PubNub handle everything.
The maximum message size is 32 KiB, including the final escaped character count and the channel name. An optimal message size is under 1800 bytes.
If the message you publish exceeds the configured size, you receive a Message Too Large
error. If you want to learn more or calculate your payload size, refer to Message Size Limit.
Message compression lets you send the message payload as the compressed body of an HTTP POST call.
Every PubNub SDK supports sending messages using the publish()
call in one or more of the following ways:
- Uncompressed, using HTTP GET (message sent in the URI)
- Uncompressed, using HTTP POST (message sent in the body)
- Compressed, using HTTP POST (compressed message sent in the body)
This section outlines what compressing a message means, and how to use compressed messages to your advantage.
Compressed messages support
Currently, the C and Objective-C SDKs support compressed messages.
Message compression can be helpful if you want to send data exceeding the default 32 KiB message size limit, or use bandwidth more efficiently. Compressing messages is useful for scenarios that include high channel occupancy and quick exchange of information like ride hailing apps or multiplayer games.
Compression Trade-offs
-
Small messages can expand.
Compressed messages generally have a smaller size, and can be delivered faster, but only if the original message is over 1 KiB. If you compress a signal (whose size is limited to 64 bytes), the compressed payload exceeds the signal's initial uncompressed size.
-
CPU overhead can increase.
While a smaller payload size is an advantage, working with compressed messages uses more CPU time than working with uncompressed messages. CPU time is required to compress the message on the sending client, and again to decompress the message on the receiving client. Efficient resource management is especially important on mobile devices, where increased usage affects battery life. Carefully consider the balance of lower bandwidth and higher speed versus any increased CPU usage.
Compression methods and support vary between SDKs. If the receiving SDK doesn't support the sender's compression method, or even if it doesn't support compression at all, the PubNub server automatically changes the compressed message's format so that it is understandable to the recipient. No action is necessary from you.
Messages are not compressed by default; you must always explicitly specify that you want to use message compression. Refer to the code below for an example of sending a compressed message.
struct pubnub_publish_options opt = pubnub_publish_defopts();
opt.method = pubnubSendViaPOSTwithGZIP;
pbresult = pubnub_publish_ex(pn, "channel_name", "{\"message\":\"This message will be compressed\"}", opt);
}]
You can publish as fast as bandwidth conditions 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, the subscriber may not receive the first 100 messages because the message queue has a limit of only 100 messages stored in memory.
- Publish to any given channel in a serial manner (not concurrently).
- Check that the return code is success (for example,
[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 according to your app's latency needs, for example no more than 5 messages per second.
Method(s)
To Publish a message
you can use the following method(s) in the C-Core SDK:
enum pubnub_res pubnub_publish (
pubnub_t *p,
const char *channel,
const char *message
)
Parameter | Type | Required | Description |
---|---|---|---|
p | pubnub_t* | Yes | Pointer to PubNub context. Can't be NULL |
channel | const char* | Yes | Pointer to string with the channel name (or comma-delimited list of channel names) to publish to. |
message | const char* | Yes | Pointer to string containing message to publish in JSON format. |
enum pubnub_res pubnub_publishv2 (
pubnub_t *p,
const char *channel,
const char *message,
bool store_in_history,
bool eat_after_reading
)
Parameter | Type | Required | Description |
---|---|---|---|
p | pubnub_t* | Yes | Pointer to Pubnub Client Context |
channel | const char* | Yes | Pointer to string with the channel name (or comma-delimited list of channel names) to publish to. |
message | const char* | Yes | Pointer to string containing message to publish in JSON format. |
store_in_history | bool | Yes | If false, message will not be stored in history of the channel |
eat_after_reading | const char* | Yes | If true, message will not be stored for delayed or repeated retrieval or display |
Basic Usage
Publish a message to a channel
pubnub_publish(ctx, "my_channel", "\"message\"");
pbresult = pubnub_await(ctx);
if (PNR_OK == pbresult) {
/* Published successfully */
}
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, "Sent", "13769558699541401"]
Other Examples
Publish a JSON serialized message
pubnub_t *ctx = pubnub_alloc();
if (NULL == ctx) {
puts("Couldn't allocate a Pubnub context");
return -1;
}
pubnub_init(ctx, "demo", "demo");
pubnub_set_user_id(ctx, "MyUniqueUser_Id");
pubnub_publish(ctx, "hello_world", "{\"msg\": \"Hello from Pubnub C-core docs!\"}");
enum pubnub_res pbresult = pubnub_await(ctx);
if (pbresult != PNR_OK) {
printf("Failed to publish, error %d\n", pbresult);
pubnub_free(ctx);
return -1;
}
Publish with cipher key
res = pubnub_publish_encrypted(pbp, chan, "\"Hello world from crypto sync!\"", cipher_key);
if (res != PNR_STARTED) {
printf("pubnub_publish() returned unexpected: %d\n", res);
pubnub_free(pbp);
return -1;
}
Publish with cipher key using pubnub_publish_ex
Using this method you can reuse the cipherKey
from the options.
struct pubnub_publish_options opt = pubnub_publish_defopts();
opt.cipher_key = my_cipher_key;
pbresult = pubnub_publish_ex(pn, "my_channel", "42", opt);
Extended Publish
Extended Publish Options structure
Holds all the options for extended
publish.
Method(s)
Declaration
struct pubnub_publish_options {
bool store;
char const *cipher_key;
bool replicate;
char const *meta;
enum pubnub_publish_method method;
}
Members
Member | Type | Description |
---|---|---|
store | bool | If true , the message is stored in history. If false , the message is not stored in history. |
cipher_key | char const* | If not NULL , the key used to encrypt the message before sending it to PubNub. Keep in mind that encryption is a CPU intensive task. Also, it uses more bandwidth, most of which comes from the fact that decrypted data is sent as Base64 encoded JSON string. This means that the actual amount of data that can be sent as encrypted in a message is at least 25% smaller (than un-encrypted). Another point to be made is that it also does some memory management (allocating and deallocating). |
replicate | bool | If true , the message is replicated, thus will be received by all subscribers. If false , the message is not replicated and will be delivered only to Function event handlers. Setting false here and false on store is referred to as a Fire (instead of a publish ). |
meta | char const* | An optional JSON object, used to send additional (meta ) data about the message, which can be used for stream filtering . |
method | enum pubnub_publish_method | Defines the method by which publish transaction will be performed. Can be HTTP GET or POST . If using POST , content can be GZIP compressed. |
Initialize extended Publish options
This returns the default options
for publish V1 transactions. Will set:
Parameter | Default |
---|---|
store | true |
cipher_key | NULL |
replicate | true |
meta | NULL |
method | pubnubPublishViaGET |
Method(s)
Declaration
struct pubnub_publish_options pubnub_publish_defopts(void);
Parameters
This method doesn't take any argument.
Basic Usage
struct pubnub_publish_options opts = pubnub_publish_defopts();
Returns
Type | Value | Description |
---|---|---|
struct pubnub_publish_options | The default options for publish . |
Extended Publish
The extended publish V1. Basically the same as pubnub_publish()
, but with added optional parameters in @p
opts.
Method(s)
Declaration
enum pubnub_res pubnub_publish_ex(
pubnub_t *p,
const char *channel,
const char *message,
struct pubnub_publish_options opts
)
Parameters
Parameter | Type | Required | Description |
---|---|---|---|
p | pubnub_t* | Yes | The Pubnub context. |
channel | char const* | Yes | The string with the channel name to publish to. |
message | char const* | Yes | The message to publish . It needs to be JSON encoded. |
opts | struct pubnub_publish_options | Yes | The Publish options. |
Basic Usage
struct pubnub_publish_options opt = pubnub_publish_defopts();
opt.store = false;
pbresult = pubnub_publish_ex(pn, "my_channel", "42", opt);
Returns
Type | Value | Description |
---|---|---|
enum pubnub_res | PNR_STARTED | Success. |
other | Indicates the type of error. |
Signal
Sends a signal @p
message (in JSON format) on @p
channel, using the @p
pb context. This actually means "initiate a signal transaction".
It has similar behavior as publish, but unlike publish transaction, signal erases previous signal message on server (on a given channel,) and you can not send any metadata.
There can be only up to one signal message at the time. If it's not renewed by another signal, signal message disappears from channel history after a certain amount of time.
You can't (send a) signal
if a transaction is in progress on @p
pb context.
If transaction is not successful (@c
PNR_PUBLISH_FAILED
), you can get the string describing the reason for failure by calling pubnub_last_publish_result()
.
Keep in mind that the timetoken from the signal operation response is not parsed by the library, just relayed to the user. Only time-tokens from the subscribe operation are parsed by the library.
Also, for all error codes known at the time of this writing, the HTTP error will also be set, so the result of the PubNub operation will not be @c
PNR_OK
(but you will still be able to get the result code and the description).
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
enum pubnub_res pubnub_signal(
pubnub_t* pb,
char const* channel,
char const* message
)
Parameters
Parameter | Type | Required | Description |
---|---|---|---|
pb | pubnub_t* | Yes | The Pubnub context in which to parse the response. |
channel | char const* | Yes | The string with the channel to signal to. |
message | char const* | Yes | The string with the signal, expected to be in JSON format. |
Basic Usage
Signal a message to a channel
enum pubnub_res = pubnub_signal(pb, "my_channel", "\"signalling\"");
Returns
Type | Value | Description |
---|---|---|
enum pubnub_res | PNR_OK | Transaction finished (signal sent). |
PNR_STARTED | Transaction started (started to send signal), will finish later. | |
otherwise | Error, value indicates the reason for failure. |
Message type enumeration (enum pubnub_message_type)
Defines the type of a message that is retrieved with subscribe V2:
Symbol | Value | Description |
---|---|---|
pbsbPublished | 0 | Published message (sent via Publish transaction) |
pbsbSignal | 1 | A signal message (sent via Signal transaction) |
Subscribe (new)
The subscribe function creates an open TCP socket to PubNub and begins listening for messages and events on a specified entity or set of entities. To subscribe successfully, you must configure the appropriate subscribeKey
at initialization.
Entities are first-class citizens that provide access to their encapsulated APIs. You can subscribe using the PubNub client object or directly on a specific entity:
A newly subscribed client receives messages after the subscribe()
call completes. You can configure automatic retries to attempt to reconnect automatically and retrieve any available messages if a client gets disconnected.
Subscription scope
Subscription objects provide an interface to attach listeners for various real-time update types. Your app receives messages and events via those event listeners. Two types of subscriptions are available:
Subscription
, created from an entity with a scope of only that entity (for example, a particular channel)SubscriptionSet
, created from the PubNub client with a global scope (for example, all subscriptions created on a singlepubnub
object ). A subscription set can have one or more subscriptions.
The event listener is a single point through which your app receives all the messages, signals, and events in the entities you subscribed to. For information on adding event listeners, refer to Event listeners.
Create a subscription
An entity-level Subscription
allows you to receive messages and events for only that entity for which it was created. Using multiple entity-level Subscription
s is useful for handling various message/event types differently in each channel.
// entity-based, local-scoped, with options
pubnub_subscription_options_t options = pubnub_subscription_options_defopts();
options.receive_presence_events = true;
pubnub_subscription_t* subscription = pubnub_subscription_alloc(
entity,
&options);
if (NULL == subscription) {
// Handle parameters error (missing entity or invalid PubNub context pointer) or insufficient memory.
}
// entity-based, local-scoped, without options
pubnub_subscription_t* subscription = pubnub_subscription_alloc(entity, NULL);
if (NULL == subscription) {
// Handle error for missing entity or invalid PubNub context pointer or insufficient memory.
}
Parameter | Type | Required | Description |
---|---|---|---|
options.receive_presence_events | bool | No | Whether presence updates for userId should be delivered through the listener streams. |
Create a subscription set
A client-level SubscriptionSet
allows you to receive messages and events for all entities. A single SubscriptionSet
is useful for similarly handling various message/event types in each channel.
// client-based, general-scoped, with options
pubnub_subscription_options_t options = pubnub_subscription_options_defopts();
options.receive_presence_events = true;
pubnub_subscription_set_t* subscription_set = pubnub_subscription_set_alloc_with_entities(
entities,
4,
&options);
if (NULL == subscription_set) {
// Handle parameters error (missing entities or invalid entity's PubNub context pointer) or insufficient memory.
}
// client-based, general-scoped, without options
pubnub_subscription_set_t* subscription_set = pubnub_subscription_set_alloc_with_entities(
entities,
4,
show all 19 linesParameter | Type | Required | Description |
---|---|---|---|
entities | pubnub_entity_t** | Yes | Pointer to the array with PubNub entities object pointers which should be used in subscriptions set. |
entities_count | int | Yes | The number of PubNub entities in array. |
options | const pubnub_subscription_options_t* | Yes | Pointer to the subscription configuration options. Set to NULL if options are not required. |
Method(s)
Subscription
and SubscriptionSet
use the same subscribe()
method.
Subscribe
To subscribe, you can use the following method in the c SDK:
enum pubnub_res pubnub_subscribe_with_subscription(
pubnub_subscription_t* sub,
const pubnub_subscribe_cursor_t* cursor);
Parameter | Type | Required | Description |
---|---|---|---|
cursor | const pubnub_subscribe_cursor_t | No | Timetoken from which to return any available cached messages. Message retrieval with timetoken is not guaranteed and should only be considered a best-effort service. If the value is not a 17-digit number, the provided value will be ignored. |
sub | pubnub_subscription_t* | No | Pointer to the subscription, which should be used with the next subscription loop. |
// subscription cursor
// timetoken is a pointer to the PubNub high-precision timetoken
pubnub_subscribe_cursor_t pubnub_subscribe_cursor(
const char* timetoken);
Basic usage
enum pubnub_res rslt = pubnub_subscribe_with_subscription(subscription, NULL);
if (PNR_OK != rslt) {
// Handle subscription error (mostly because of parameters error).
}
Returns
The subscribe()
method doesn't have a return value.
Entities
Entities are subscribable objects for which you can receive real-time updates (messages, events, etc).
Create channels
This method returns a local Channel
entity.
pubnub_channel_t* pubnub_channel_alloc(
pubnub_t* pb,
const char* name);
Parameter | Type | Required | Description |
---|---|---|---|
pb | pubnub_t* | Yes | Pointer to the PubNub context used by the created entity to interact with PubNub REST API. |
name | const char* | Yes | Pointer to the name of the channel to create. |
Basic usage
pubnub_channel_t* channel = pubnub_channel_alloc(pb, "my_channel");
Create channel groups
This method returns a local Channel Group
entity.
pubnub_channel_group_t* pubnub_channel_group_alloc(
pubnub_t* pb,
const char* name);
Parameter | Type | Required | Description |
---|---|---|---|
pb | pubnub_t* | Yes | Pointer to the PubNub context used by the created entity to interact with PubNub REST API. |
name | const char* | Yes | Pointer to the name of the channel group to create. |
Basic usage
pubnub_channel_group_t* group = pubnub_channel_group_alloc(pb, "my_group");
Create channel metadata
This method returns a local Channel Metadata
entity.
pubnub_channel_metadata_t* pubnub_channel_metadata_alloc(
pubnub_t* pb,
const char* id);
Parameter | Type | Required | Description |
---|---|---|---|
pb | pubnub_t* | Yes | Pointer to the PubNub context used by the created entity to interact with PubNub REST API. |
id | const char* | Yes | The String identifier of the channel metadata object to create. |
Basic usage
pubnub_channel_metadata_t* metadata = pubnub_channel_metadata_alloc(pb, "channel_meta");
Create user metadata
This method returns a local User Metadata
entity.
pubnub_user_metadata_t* pubnub_user_metadata_alloc(
pubnub_t* pb,
const char* id);
Parameter | Type | Required | Description |
---|---|---|---|
pb | pubnub_t* | Yes | Pointer to the PubNub context used by the created entity to interact with PubNub REST API. |
id | const char* | Yes | The String identifier of the user metadata object to create a subscription of. |
Basic usage
pubnub_user_metadata_t* metadata = pubnub_user_metadata_alloc(pb, "user_meta");
Event listeners
Messages and events are received in your app using a listener. This listener allows a single point to receive all messages, signals, and events.
You can attach listeners to the instances of Subscription
, Subscription Set
, and, in the case of the connection status, the PubNub client.
Add listeners
You can implement multiple listeners or register an event-specific listener that receives only a selected type, like message
or file
.
Method(s)
// Add event-specific listeners
// reacts to all subscriptions on a given pubnub object
enum pubnub_res pubnub_subscribe_add_message_listener(
const pubnub_t* pb,
pubnub_subscribe_listener_type type,
pubnub_subscribe_message_callback_t callback);
// reacts to a specific event type on a given subscription
enum pubnub_res pubnub_subscribe_add_subscription_listener(
const pubnub_subscription_t* subscription,
pubnub_subscribe_listener_type type,
pubnub_subscribe_message_callback_t callback);
// reacts to a specific event type on a given subscription set
show all 52 linesParameter | Type | Required | Description |
---|---|---|---|
pb | pubnub_t* | Yes | Pointer to the PubNub context used by the created entity to interact with PubNub REST API. |
type | pubnub_subscribe_listener_type | Yes | Type of real-time update for which listener will be called. Available types include: LISTENER_ON_MESSAGE , LISTENER_ON_SIGNAL , LISTENER_ON_MESSAGE_ACTION , LISTENER_ON_OBJECTS , and LISTENER_ON_FILES . |
callback | pubnub_subscribe_message_callback_t | Yes | Function to handle the listener status change. |
Add connection status listener
The PubNub client has a listener dedicated to handling connection status updates.
Client scope
This listener is only available on the PubNub object.
Method(s)
// add status listener
enum pubnub_res pubnub_subscribe_add_status_listener(
const pubnub_t* pb,
pubnub_subscribe_status_callback_t callback);
// remove status listener
enum pubnub_res pubnub_subscribe_remove_status_listener(
const pubnub_t* pb,
pubnub_subscribe_status_callback_t callback);
Parameter | Type | Required | Description |
---|---|---|---|
pb | pubnub_t* | Yes | Pointer to the PubNub context used by the created entity to interact with PubNub REST API. |
callback | pubnub_subscribe_message_callback_t | Yes | Function to handle the listener status change. |
Basic usage
void subscribe_status_change_listener(
const pubnub_t* pb,
const pubnub_subscription_status status,
const pubnub_subscription_status_data_t status_data)
{
// Handle new subscription status
}
// Add listener
pubnub_subscribe_add_status_listener(pb, subscribe_status_change_listener);
// Remove listener
pubnub_subscribe_remove_status_listener(pb, subscribe_status_change_listener);
Returns
The subscription status. For information about available statuses, refer to SDK statuses.
Unsubscribe
Stop receiving real-time updates from a Subscription
or a SubscriptionSet
.
Method(s)
enum pubnub_res pubnub_unsubscribe_with_subscription(
pubnub_subscription_t** sub);
enum pubnub_res pubnub_unsubscribe_with_subscription_set(
pubnub_subscription_set_t** set);
Basic Usage
enum pubnub_res rslt = pubnub_unsubscribe_with_subscription(&subscription);
if (PNR_OK != rslt) {
// handle unsubscription error (mostly because of parameters error).
}
Returns
None
Unsubscribe All
Stop receiving real-time updates from all data streams and remove the entities associated with them.
Client scope
This method is only available on the PubNub object.
Method(s)
enum pubnub_res pubnub_unsubscribe_all(const pubnub_t* pb);
Basic Usage
enum pubnub_res rslt = pubnub_unsubscribe_all(pb);
if (PNR_OK != rslt) {
// handle unsubscribe all error
}
Returns
None
Subscribe (old)
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
. To subscribe to a channel
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 pubnub_subscribe()
call completes.
Message retrieval
Typically, you will want two separate contexts for publish and subscribe. When changing the active set of subscribed channels, first call pubnub_leave()
on the old set. The pubnub_subscribe()
interface is essentially a transaction to start listening on the channel for arrival of next message. This has to be followed by pubnub_get()
call 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 C-Core SDK:
enum pubnub_res pubnub_subscribe(
pubnub_t *p,
const char *channel,
const char *channel_group
)
Parameter | Type | Required | Description |
---|---|---|---|
p | pubnub_t* | Yes | Pointer to PubNub client context. Can't be NULL. |
channel | const char* | Optional | The string with the channel name (or comma-delimited list of channel names) to subscribe to. |
channel_group | const char* | Optional | The string with the channel group name (or comma-delimited list of channel group names) to subscribe to. |
Basic Usage
Subscribe to a channel:
pubnub_subscribe(ctx, "my_channel", NULL);
pbresult = pubnub_await(ctx);
if (PNR_OK == pbresult) {
char const *message = pubnub_get(ctx);
while (message != NULL) {
message = pubnub_get(ctx);
}
}
Rest Response from Server
The output below demonstrates the response format to a successful call:
[[], "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.
pubnub_t *ctx = pubnub_alloc();
if (NULL == ctx) {
puts("Couldn't allocate a Pubnub context");
return -1;
}
pubnub_init(ctx, "demo", "demo");
pubnub_set_user_id(ctx, "MyUniqueUser_Id")
pubnub_subscribe(ctx, "hello_world1,hello_world2,hello_world3", NULL);
pbresult = pubnub_await(ctx);
if (pbresult != PNR_OK) {
printf("Failed to subscribe, error %d\n", pbresult);
pubnub_free(ctx);
return -1;
}
else {
show all 24 linesSubscribing to a Presence channel
Requires Presence add-on
This method requires that the Presence add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.
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
.
// Sync
char *presence_channel = malloc(strlen(channel) + strlen(PUBNUB_PRESENCE_SUFFIX) + 1);
strcpy(presence_channel, channel);
strcat(presence_channel, PUBNUB_PRESENCE_SUFFIX);
pubnub_subscribe(ctx, presence_channel, NULL);
pbresult = pubnub_await(ctx);
if (PNR_OK == pbresult) {
char const *presence_event = pubnub_get(ctx);
while (presnce_event != NULL) {
presence_event = pubnub_get(ctx);
}
}
// Callback
show all 44 linesSample Responses
Join Event
{
"action": "join",
"timestamp": 1345546797,
"uuid": "175c2c67-b2a9-470d-8f4b-1db94f90e39e",
"occupancy": 2
}
Leave Event
{
"action" : "leave",
"timestamp" : 1345549797,
"uuid" : "175c2c67-b2a9-470d-8f4b-1db94f90e39e",
"occupancy" : 1
}
Timeout Event
{
"action": "timeout",
"timestamp": 1345549797,
"uuid": "76c2c571-9a2b-d074-b4f8-e93e09f49bd",
"occupancy": 0
}
Custom Presence Event (State Change)
{
"action": "state-change",
"uuid": "76c2c571-9a2b-d074-b4f8-e93e09f49bd",
"timestamp": 1345549797,
"data": {
"isTyping": true
}
}
Interval Event
{
"action":"interval",
"timestamp":1474396578,
"occupancy":2
}
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 user_ids since the last interval message.
- joined
- left
- timedout
For example, this interval message indicates there were 2 new user_ids that joined and 1 timed out user_id since the last interval:
{
"action" : "interval",
"occupancy" : <# users in channel>,
"timestamp" : <unix timestamp>,
"joined" : ["uuid2", "uuid3"],
"timedout" : ["uuid1"]
}
If the full interval message is greater than 30KB
(since the max publish payload is ∼32KB
), 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.
{
"action" : "interval",
"occupancy" : <# users in channel>,
"timestamp" : <unix timestamp>,
"here_now_refresh" : true
}
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.
enum pubnub_res res;
for (;;) {
res = pubnub_subscribe(pn, NULL, channel_group);
read_response(pn, res);
}
Subscribe to the presence channel of a channel group
note
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.
enum pubnub_res res;
for (;;) {
res = pubnub_subscribe(pn, NULL, "family-pnpres");
read_response(pn, res);
}
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:
char msg[MAX_MSG_LEN];
pbresult = pubnub_get_decrypted(pn, my_cipher_key, s, sizeof s);
if (PNR_OK == pbresult) {
/* Use the message in `msg` */
}
or, for a different usability/safety trade-off:
pubnub_bymebl_t msg = pubnub_get_decrypted_alloc(pn, my_cipher_key);
if (msg.ptr != NULL) {
/* use the message in `msg.ptr` */
free(msg.ptr);
}
Extended Subscribe (old)
Extended Subscribe Options structure
Holds all the options for extended
subscribe.
Method(s)
Declaration
struct pubnub_subscribe_options {
char const* channel_group;
unsigned heartbeat;
}
Members
Member | Type | Description |
---|---|---|
channel_group | char const* | Channel group (a comma-delimited list of channel group names). If NULL , will not be used. |
cipher_key | char const* | The channel activity timeout , in seconds. If below the minimum value supported by Pubnub, the minimum value will be used (instead). |
Initialize extended Subscribe options
This returns the default options for subscribe transactions. Will set channel_group = NULL
and heartbeat
to default heartbeat value.
Method(s)
Declaration
struct pubnub_subscribe_options pubnub_subscribe_defopts(void)
Parameter
This method doesn't take any arguments.
Basic Usage
struct pubnub_subscribe_options opts = pubnub_subscribe_defopts();
Returns
Type | Value | Description |
---|---|---|
struct pubnub_subscribe_options | The default options for subscribe. |
Extended Subscribe
The extended subscribe. Basically the same as pubnub_subscribe()
but with options except @p
channel given in @p
opts.
Method(s)
Declaration
enum pubnub_res pubnub_subscribe_ex(
pubnub_t* p,
const char* channel,
struct pubnub_subscribe_options opts
)
Parameter
Parameter | Type | Required | Description |
---|---|---|---|
p | pubnub_t* | Yes | The Pubnub context. |
channel | char const* | Yes | The string with the channel name (or comma-delimited list of channel names) to subscribe for. |
opts | struct pubnub_subscribe_options | Yes | Subscribe options. |
Basic Usage
struct pubnub_subscribe_options opt = pubnub_subscribe_defopts();
opt.heartbeat = 412;
pbresult = pubnub_subscribe_ex(pn, "my_channel", opt);
Returns
Type | Value | Description |
---|---|---|
enum pubnub_res | PNR_STARTED | Success. |
other | Indicates the type of error. |
Subscribe v2 (old)
Subscribe v2 Options structure
Holds all the options for subscribe v2.
Method(s)
Declaration
struct pubnub_subscribe_v2_options {
char const* channel_group;
unsigned heartbeat;
}
Members
Member | Type | Description |
---|---|---|
channel_group | char const* | Channel group (a comma-delimited list of channel group names). If NULL , will not be used. |
heartbeat | unsigned | The channel activity timeout, in seconds. If below the minimum value supported by Pubnub, the minimum value will be used (instead). |
char const* | filter_expr | The filter expression to apply. It's a predicate to apply to the metadata of a message. If it returns true , message will be received, otherwise, it will be skipped (as if not published). Syntax is not trivial, but can be described as mostly Javascript on the metadata (which is JSON, thus, "integrates well" with Javascript). For example, if your metadata is: {"zec":3} , then this filter _would_ match it: zec==3 , while zec==4 would _not_ . If message doesn't have metadata, this will be ignored. If NULL , will not be used. |
Initialize extended Subscribe v2 options
This returns the default options for subscribe transactions. Will set channel_group
= NULL
, heartbeat
to default heartbeat value and filter_expr
= NULL
.
Method(s)
Declaration
struct pubnub_subscribe_v2_options pubnub_subscribe_v2_defopts(void)
Parameter
This method doesn't take any arguments.
Basic Usage
struct pubnub_subscribe_v2_options opts = pubnub_subscribe_v2_defopts();
Returns
Type | Value | Description |
---|---|---|
struct pubnub_subscribe_options | The default options for subscribe. |
Subscribe v2
The V2 subscribe. To get messages for subscribe V2, use pubnub_get_v2()
- keep in mind that it can provide you with channel and channel group info.
Method(s)
Declaration
enum pubnub_res pubnub_subscribe_v2(
pubnub_t *p,
const char *channel,
struct pubnub_subscribe_v2_options opts
)
Parameter
Parameter | Type | Required | Description |
---|---|---|---|
p | pubnub_t* | Yes | The Pubnub context. |
channel | char const* | Yes | The string with the channel name (or comma-delimited list of channel names) to subscribe for. |
opts | struct pubnub_subscribe_options | Yes | Subscribe V2 options. |
Basic Usage
struct pubnub_subscribe_v2_options opt = pubnub_subscribe_v2_defopts();
opt.heartbeat = 412;
pbresult = pubnub_subscribe_v2(pn, "my_channel", opt);
Returns
Type | Value | Description |
---|---|---|
enum pubnub_res | PNR_STARTED | Started. |
PNR_OK | Finished with a success (can only happen in the sync interface). | |
other | Failed, Indicates the type of error. |
V2 message structure
Pubnub V2 message has lots of data and here's how we express them for the pubnub_get_v2()
.
The "string fields" are expressed as Pascal strings, that is, a pointer with string length, and don't include a NUL
character. Also, these pointers are actually pointing into the full received subscribe response, so, their lifetime is tied to the message lifetime and any subsequent transaction on the same context will invalidate them.
If a (string) field is not present, it will empty, meaning its size (length) will be zero and pointer (start) should be NULL
(it might not be NULL
, it's best to rely on size).
Method(s)
Declaration
struct pubnub_v2_message {
char const* channel_group;
unsigned heartbeat;
}
Parameter
Member | Type | Description |
---|---|---|
tt | struct pubnub_char_mem_blok | The timetoken of the message - when it was published. |
region | int | Region of the message - not interesting in most cases. |
flags | int | Message flags (indicators). |
channel | struct pubnub_char_mem_blok | Channel that message was published to. |
match_or_group | struct pubnub_char_mem_blok | Subscription match or the channel group. |
payload | struct pubnub_char_mem_blok | The message itself (its contents, payload). |
metadata | struct pubnub_char_mem_blok | The message metadata, as published. |
message_type | enum pubnub_message_type | The type of the message (published , signal ). |
Get V2 message
Parse and return the next V2 message, if any.
Do keep in mind that you can use pubnub_get()
to get the full message array in JSON, but, then you'll have to parse it yourself, and pubnub_channel()
and pubnub_channel_group()
would not work. On the other hand, this function will fail if you use it on subscribe v1 response.
If there are no more messages, this will return a struct memset to zero
. It's best to check if payload is empty, as there has to be a payload, while other fields/attributes are mostly optional.
Method(s)
Declaration
struct pubnub_v2_message pubnub_get_v2(pubnub_t* pbp)
Parameter
Parameter | Type | Required | Description |
---|---|---|---|
pbp | pubnub_t* | Yes | The Pubnub context from which to get the next message. |
Basic Usage
struct pubnub_v2_message msg;
for (msg = pubnub_get_v2(pbp); msg.payload.size > 0; msg = pubnub_get_v2(pbp)) {
puts("Received message:");
printf(" Channel = '%.*s'\n", (int)msg.channel.size, msg.channel.ptr);
printf(" Timetoken = '%.*s'\n", (int)msg.tt.size, msg.tt.ptr);
printf(" Metadata = '%.*s'\n", (int)msg.metadata.size, msg.metadata.ptr);
printf(" Payload = '%.*s'\n", (int)msg.payload.size, msg.payload.ptr);
}
Returns
Type | Value | Description |
---|---|---|
struct pubnub_v2_message | The V2 message structure describing the next V2 message in the subscribe response. If there is no next message (response is empty, or subscribe V1, or some other transaction), the payload of the message will be empty. |
Unsubscribe (old)
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:- Set the context to use
non-blocking I/O
- Wait for the outcome in a loop, checking for
pubnub_last_result()
- rather than callingpubnub_await()
- If a condition occurs that prompts you to
unsubscribe
, callpubnub_cancel()
- Wait for the cancellation to finish (here you can call
pubnub_await()
, unless you want to do other stuff while you wait)
- Set the context to use
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 C-Core SDK:
Parameter | Type | Required | Description |
---|---|---|---|
p | pubnub_t* | Yes | Pointer to Pubnub Client Context. |
Basic Usage
Unsubscribe from a channel:
pbresult = pubnub_subscribe(ctx, "my_channel", NULL);
/* If we don't set non-blocking I/O, we can't get out of a blocked read */
pubnub_set_non_blocking_io(ctx);
/* Can't use pubnub_await() here, it will block */
while (PNR_STARTED == pbresult) {
pbresult = pubnub_last_result(ctx);
/* Somehow decide we want to quit / unsubscribe */
if (should_stop()) {
pubnub_cancel(ctx);
/* If we don't have anything else to do, it's OK to await now,
but you could again have a loop "against" pubnub_last_result()
*/
pbresult = pubnub_await(ctx);
break;
}
show all 19 linesRest Response from Server
The output below demonstrates the response to a successful call:
{
"action" : "leave"
}
Other Examples
Unsubscribing from a channel group
pbresult = pubnub_subscribe(ctx, NULL, "my_channel_group");
/* If we don't set non-blocking I/O, we can't get out of a blocked read */
pubnub_set_non_blocking_io(ctx);
/* Can't use pubnub_await() here, it will block */
while (PNR_STARTED == pbresult) {
pbresult = pubnub_last_result(ctx);
/* Somehow decide we want to quit / unsubscribe */
if (should_stop()) {
pubnub_cancel(ctx);
/* If we don't have anything else to do, it's OK to await now,
* but you could again have a loop "against" pubnub_last_result()
*/
pbresult = pubnub_await(ctx);
break;
}
show all 19 lines