Publish/Subscribe API for PubNub Rust 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 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 | Type | Required | Default | Description |
---|---|---|---|---|
publish_message | T: Serialize | Yes | The message payload. Any type that implements the Serialize trait is allowed. | |
channel | Into<String> | Yes | The channel to send the message to. | |
store | Option<bool> | Optional | Account default | Whether to store the messages in Message Persistence or not. |
meta | Option<HashMap<String, String>> | Optional | A hash map of additional information about the message you can use for Filters. | |
replicate | bool | Optional | Whether to replicate the messages across points of presence or not. Refer to Replicated Transactions for more information. | |
ttl | Option<u32> | Optional | 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. 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 | bool | Optional | false | Whether to use HTTP POST to publish the message. |
execute | Yes | false | Executes the request based on the provided data. This function returns a Future and you must .await the value. |
Basic Usage
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
Receive messages
Your app receives messages and events via event listeners. The event listener is a single point through which your app receives all the messages, signals, and events that are sent in any channel you are subscribed to.
For more information about adding a listener, refer to the Event Listeners section.
Description
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 subscribe()
call completes.
If a client gets disconnected from a channel, it can automatically attempt to reconnect to that channel
and retrieve any available messages that were missed during that period. This can be achieved by setting with_retry_policy()
to RequestRetryPolicy::Linear
, when initializing the client.
Method(s)
To subscribe to a channel you can use the following method(s) in the Rust SDK:
pubnub
.subscribe()
.channels(Vec<String>)
.channel_groups(Vec<String>)
.cursor(u64)
.heartbeat(u32)
.filter_expression(String)
Parameter | Type | Required | Description |
---|---|---|---|
channels() | Vec<String> | Either channels() or channel_groups() is required. | Channels to subscribe to. |
channel_groups() | Vec<String> | Either channels() or channel_groups() is required. | Channel groups to subscribe to. |
cursor() | u64 | Optional | Timetoken allowing you to subscribe from a specific point in time. |
heartbeat() | u32 | Optional | Interval (in seconds) in which the client annouces itself to the server. |
filter_expression() | String | Optional | String allowing the client to only receive messages that satisfy the conditions of the filter. The message filter is set by the subscribing client(s) but it is applied on the server side thus preventing unwanted messages (those that do not meet the conditions of the filter) from reaching the subscriber. For more information, refer to the Publish Messages documentation. |
Basic Usage
Subscribe to a channel with automatic connection handling:
Event listeners
The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method.
Returns
The subscribe()
operation returns a Subscription
which implements the stream trait and contains a SubscribeStreamEvent
as its item.
SubscribeStreamEvent
has the following variants:
Variant | Type | Description |
---|---|---|
Status | SubscribeStatus | Status of the subscription. Available statuses:
|
Update | Update | The actual real-time update, like a message or a presence update. |
The Update
enum contains the following variants:
Variant | Description |
---|---|
Presence | Presence change real-time update. Payload represents one of the presence types:
|
Object | Object (App Context) real-time update. |
MessageAction | Messages reactions real-time update. |
File | File sharing real-time update. |
Message | Real-time message update. |
Signal | Real-time signal update. |
Other Examples
Raw asynchronous subscribe with no connection handling
Raw synchronous subscribe with no connection handling
Only receive message updates
let subscription = client
.subscribe()
.channels(["my_channel".into(), "other_channel".into()].to_vec())
.heartbeat(10)
.filter_expression("some_filter")
.execute()?;
tokio::spawn(async move {
let mut message_stream = subscription.message_stream();
while let Some(update) = message_stream.next().await {
match update {
Update::Message(message) => {
// Deserialize the message payload as you wish
match serde_json::from_slice::<Message>(&message.data) {
Ok(message) => println!("defined message: {:?}", message),
show all 24 linesOnly receive status updates
let subscription = client
.subscribe()
.channels(["my_channel".into(), "other_channel".into()].to_vec())
.heartbeat(10)
.filter_expression("some_filter")
.execute()?;
tokio::spawn(async move {
let mut status_stream = subscription.status_stream();
while let Some(status) = status_stream.next().await {
println!("\nstatus: {:?}", status);
}
});
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 a vector to specify the channel names.
Unsubscribe
When subscribed to a single channel, this function causes the client to issue a leave
from the channel
and close any open socket to the PubNub Network. For multiplexed channels, the specified channel
(s) will be removed and the socket remains open until there are no more channels remaining in the list.
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 Rust SDK:
subscription
.unsubscribe();
Basic Usage
Unsubscribe from a channel:
subscription.unsubscribe().await;
Event listeners
The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method.
Returns
This method doesn't return anything. Note that the Subscription
entity will cease to exist and will no longer be usable.