Rust API & SDK Docs 0.6.0

In this guide, we'll create a simple "Hello, World" application that demonstrates the core concepts of PubNub:

  • Setting up a connection
  • Sending messages
  • Receiving messages in real-time

Overview

This guide will help you get up and running with PubNub in your Rust application. Since Rust is commonly used across different platforms, we provide two implementation paths:

  • Server-side applications: For developers building backend services and applications with Rust
  • Embedded systems: For developers using Rust in resource-constrained environments (embedded devices, WebAssembly)

The core PubNub concepts and API usage remain the same across both paths, but implementation details like feature selection and memory management differ. Select the appropriate tab in each section to see platform-specific guidance.

Feature selection

The Rust SDK is designed to be modular with support for different feature sets. You can enable or disable specific features based on your needs, which is especially useful for embedded systems with limited resources.

Prerequisites

Before we dive in, make sure you have:

  • A basic understanding of Rust
  • Rust and Cargo installed on your system
  • A PubNub account (we'll help you set this up!)

Setup

Get your PubNub keys

First things first – you'll need your PubNub keys to get started. Here's how to get them:

  • Sign in or create an account on the PubNub Admin Portal
  • Create a new app (or use an existing one)
  • Find your publish and subscribe keys in the app's dashboard

When you create a new app, PubNub automatically generates your first set of keys. While you can use the same keys for development and production, we recommend creating separate keysets for each environment for better security and management.

Install the SDK

SDK version

Always use the latest SDK version to have access to the newest features and avoid security vulnerabilities, bugs, and performance issues.

Add pubnub to your Rust project in the Cargo.toml file:

[dependencies]
pubnub = "0.6.0"
serde = "1.0"
serde_json = "1.0"
tokio = { version = "1", features = ["full"] }

Then in your main.rs file:

use pubnub::dx::*;
use pubnub::core::*;
use serde_json::json;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Set up PubNub configuration
let pubnub = PubNubClientBuilder::with_reqwest_transport()
.with_keyset(Keyset {
subscribe_key: "demo", // Replace with your subscribe key
publish_key: Some("demo"), // Replace with your publish key
secret_key: None,
})
.with_user_id("rust-server-user")
.build()?;
show all 22 lines

You can also download the source code directly from the GitHub repository.

Steps

Initialize PubNub

In your Rust project, create a new file (e.g., main.rs) with the following content. This is the minimum configuration you need to send messages with PubNub.

Make sure to replace the placeholder keys with your publish and subscribe keys from the Admin Portal.

use pubnub::dx::*;
use pubnub::core::*;
use serde_json::json;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Set up PubNub configuration
let pubnub = PubNubClientBuilder::with_reqwest_transport()
.with_keyset(Keyset {
subscribe_key: "demo", // Replace with your subscribe key
publish_key: Some("demo"), // Replace with your publish key
secret_key: None,
})
.with_user_id("rust-server-user")
.build()?;
show all 22 lines

For more information, refer to the Configuration section of the SDK documentation.

Set up event listeners

Listeners help your app react to events and messages. You can implement custom app logic to respond to each type of message or event.

Using Rust's async streams makes it easy to process events as they arrive:

// Import required event handling traits
use pubnub::dx::subscribe::Update;
use pubnub::subscribe::{Subscriber, EventSubscriber};
use futures::StreamExt;

// Listen for client status changes
tokio::spawn(pubnub.status_stream().for_each(|status| async move {
println!("\nStatus: {:?}", status)
}));

// Listen for all subscription events
tokio::spawn(subscription.stream().for_each(|event| async move {
match event {
Update::Message(message) | Update::Signal(message) => {
// Process incoming messages
show all 35 lines

If you only want to listen for specific events, you can use specialized streams:

// Only listen for message events on a specific channel
tokio::spawn(
channel_subscription
.messages_stream()
.for_each(|message| async move {
if let Ok(utf8_message) = String::from_utf8(message.data.clone()) {
if let Ok(cleaned) = serde_json::from_str::<String>(&utf8_message) {
println!("Message received: {}", cleaned);
}
}
})
);

For more information, refer to the Event Listeners section of the SDK documentation.

Create a subscription

To receive messages sent to a particular channel, you need to subscribe to it. This setup allows you to receive real-time updates whenever anyone publishes to that channel.

Create a subscription to one or more channels using the subscription parameters:

use pubnub::subscribe::SubscriptionParams;

// Subscribe to a single channel
let subscription = pubnub.subscription(SubscriptionParams {
channels: Some(&["my_channel"]),
channel_groups: None,
options: None
});

// Or create a subscription from a channel entity
let channel = pubnub.channel("my_channel");
let channel_subscription = channel.subscription(None);

// Activate the subscriptions
subscription.subscribe();
show all 18 lines

Publish messages

When you publish a message to a channel, PubNub delivers that message to everyone who is subscribed to that channel. A message can be any type of JSON-serializable data smaller than 32 KiB.

Let's publish a message to our channel:

// Wait a moment for the subscription to establish
tokio::time::sleep(tokio::time::Duration::from_secs(2)).await;

// Send a message to the channel
match pubnub
.publish_message("hello world!")
.channel("my_channel")
.r#type("text-message") // Optional: specify a message type
.execute()
.await {
Ok(result) => {
println!("Message published successfully! Timetoken: {}", result.timetoken);
}
Err(err) => {
println!("Failed to publish message: {:?}", err);
show all 17 lines

Clean up resources

When your application is shutting down or a component using PubNub is being removed, it's important to properly clean up resources to avoid memory leaks and ensure network connections are closed gracefully.

To properly clean up resources, unsubscribe from channels and remove listeners:

// Unsubscribe from the channel
subscription.unsubscribe();

// Remove listeners to avoid memory leaks
pubnub.remove_all_listeners();

// For more thorough cleanup, you can also destroy the client
// which will unsubscribe from all channels and remove all listeners
pubnub.destroy();

println!("Cleaned up PubNub resources");

This is particularly important in long-running applications that may create and dispose of multiple PubNub clients or subscriptions.

Run the app

To run your application:

  1. Make sure all the code is in your main.rs file.
  2. Run it with cargo run in your terminal.

If you're using async code, make sure your Cargo.toml includes tokio:

[dependencies]
pubnub = "0.6.0"
serde = "1.0"
serde_json = "1.0"
tokio = { version = "1", features = ["full"] }

And your main function should have the tokio runtime attribute:

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Your code here
Ok(())
}

When you run the application, you should see output similar to the following:

PubNub client initialized successfully!
Subscribed to channel: my_channel
Connected to PubNub network
Message published successfully! Timetoken: 16967543908123456
Received message on channel 'my_channel': {"text":"Hello, world!","sender":"Rust Server"}
Global listener: Received message on channel 'my_channel': {"text":"Hello, world!","sender":"Rust Server"}

Complete example

Here's the complete working example that puts everything together:

use pubnub::subscribe::Subscriber;
use futures::StreamExt;
use tokio::time::sleep;
use std::time::Duration;
use serde_json;
use pubnub::{
dx::subscribe::Update,
subscribe::{EventSubscriber, EventEmitter, SubscriptionParams},
Keyset, PubNubClientBuilder,
};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Set up PubNub configuration
let publish_key = "demo"; // Replace with your publish key
show all 117 lines

Troubleshooting

If you don't see the expected output, here are some common issues and how to fix them:

IssuePossible Solutions
No connection message
  • Check your internet connection.
  • Verify your publish and subscribe keys are correct.
  • Make sure you're not behind a firewall blocking PubNub's connections.
Message not received
  • Double-check that you're subscribed to the correct channel.
  • Verify that the message was actually sent (check for any error messages).
  • Make sure you're waiting long enough for the message to be delivered.
Build errors
  • Ensure you've added the PubNub dependency correctly.
  • Check that you're using a compatible version of Rust (1.65.0+ is recommended).
  • Make sure all imports are correct.
Runtime errors
  • If using async code, ensure you've set up the tokio runtime correctly.
  • Make sure you're handling errors properly with proper match statements or the ? operator.

Next steps

Great job! 🎉 You've successfully created your first PubNub application with Rust. Here are some exciting things you can explore next:

Last updated on