Publish/Subscribe API for Rust SDK
The foundation of the PubNub service is the ability to send a message and have it delivered anywhere in less than 30ms. 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 publish_message()
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.
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, Integers, and Strings. data
should not contain special classes or functions as these will not serialize. String content can include any single-byte or multi-byte UTF-8 character.
Don't JSON serialize
It is important to note that you should not JSON serialize when sending signals/messages via PUBNUB. Why? Because the serialization is done for you automatically. Instead, just pass the full object as the message payload. PubNub takes care of everything for you.
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.
Message too large error
If the message size exceeds 32KiB, you receive an appropriate error response.
For further details, check the support article.
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 (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 in accordance with your app's latency needs, for example, Publish no faster than 5 messages per second to any one channel.
Method(s)
To Publish a message you can use the following method(s) in the Rust SDK:
pubnub
.publish_message(T: Serialize)
.channel(Into<String>)
.store(Option<bool>)
.meta(Option<HashMap<String, String>>)
.replicate(bool)
.ttl(Option<u32>)
.use_post(bool)
.execute()
Parameter | Description |
---|---|
publish_message *Type: T: Serialize Default: n/a | The message payload. Any type that implements the Serialize trait is allowed. |
channel *Type: Into<String> Default: n/a | The channel ID to send the message to. |
store Type: Option<bool> Default: Account default | Whether to store the messages in Message Persistence or not. |
meta Type: Option<HashMap<String, String>> Default: n/a | A hash map of additional information about the message you can use for Filters. |
replicate Type: bool Default: n/a | Whether to replicate the messages across points of presence or not. Refer to Replicated Transactions for more information. |
ttl Type: Option<u32> Default: n/a | A per message time to live in Message Persistence. 1. If store = true , and ttl = 0 , the message is stored with no expiry time. 2. If store = true and ttl = X (X is an Integer value), the message is stored with an expiry time of X hours unless you have message retention set to Unlimited on your keyset configuration in the Admin Portal. 3. If store = false , the ttl parameter is ignored. 4. If ttl isn't specified, then expiration of the message defaults back to the expiry value for the key. |
use_post Type: bool Default: false | Whether to use HTTP POST to publish the message. |
execute *Type: Default: false | Executes the request based on the provided data. This function returns a Future and you must .await the value. |
Sample code
Publish a message to a channel:
Other examples
Returns
The publish()
operation returns a PublishResult
which contains the timetoken, or a PubNub Error
which contains the error indicator and the description of the error.
// success example
PublishResult { timetoken: "16808621084073203" }
// failure example
Error: PublishError("Status code: 400, body: OtherResponse { status: 400, error: true, service: \"Access Manager\", message: \"Invalid Subscribe Key\" }")
Subscribe
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 subscribe_key
at initialization.
Conceptual overview
For more general information about subscriptions, refer to Subscriptions.
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 with_retry_policy()
to automatically attempt to reconnect 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
let channel = client.channel("channelName");
channel.subscription(options: Option<Vec<SubscriptionOptions>>)
Parameter | Description |
---|---|
options *Type: Option<Vec<SubscriptionOptions>> | Subscription behavior configuration. Pass None for no options. |
Create a subscription set
A client-level SubscriptionSet
allows you to receive messages and events for all entities in the set. A single SubscriptionSet
is useful for similarly handling various message/event types in each channel.
// client-based, general-scoped
pubnub.subscription(parameters: (SubscriptionParams {
channels: Option<&[String]>,
channel_groups: Option<&[String]>,
options: Option<Vec<SubscriptionOptions>>
}))
Parameter | Description |
---|---|
parameters *Type: SubscriptionParams<String> | Additional Subscription configuration. |
→ channels *Type: Option<&[String]> | Subscription behavior configuration. Pass None for no options. |
→ channel_groups *Type: Option<&[String]> | Subscription behavior configuration. Pass None for no options. |
→ options *Type: Option<Vec<SubscriptionOptions>> | Subscription behavior configuration. Pass None for no options. |
Add/remove sets
You can add and remove subscription sets to create new sets. Refer to the Other examples section for more information.
SubscriptionOptions
SubscriptionOptions
is an enum. Available variants include:
Option | Description |
---|---|
ReceivePresenceEvents | Whether presence updates for userId s should be delivered through the listener streams. For information on how to receive presence events and what those events are, refer to Presence Events. |
Method(s)
Subscription
and SubscriptionSet
use the same methods to subscribe: