Store realtime message streams for future retrieval and playback

Storage And Playback Quickstart

Never lose data. Store and retrieve message history, and use message catchup when disconnected.

Storage And Playback Quickstart

1

Install PubNub

To start publishing and subscribing, we first need to access PubNub libraries. Include the libraries from CDN or from popular package managers.

View Full JavaScript SDK Documentation
<!-- Include the PubNub Library -->
<script src="https://cdn.pubnub.com/sdk/javascript/pubnub.4.27.3.js"></script>
View Full Android SDK Documentation
// Using Maven
<dependency>
  <groupId>com.pubnub</groupId>
  <artifactId>pubnub-gson</artifactId>
  <version>4.29.2</version>
</dependency>
View Full iOS SDK Documentation
# Create framework using cocoapods
git clone git@github.com:pubnub/objective-c.git

pod install
View Full .NET SDK Documentation
// Using Nuget
https://www.nuget.org/packages/Pubnub/4.5.0.0
/***************
For the 70+ SDKs that PubNub supports go to:
http://www.pubnub.com/docs
****************/

2

Instantiate PubNub

Now you can instantiate a PubNub object using your own publish and subscribe keys.

<!-- Instantiate PubNub -->
<script type="text/javascript">
    var pubnub = new PubNub({
        publishKey: "myPublishKey",
        subscribeKey: "mySubscribeKey",
        ssl: true
    });
</script>
/* Instantiate PubNub */
PNConfiguration pnConfiguration = new PNConfiguration();
pnConfiguration.setPublishKey("myPublishKey");
pnConfiguration.setSubscribeKey("mySubscribeKey");

PubNub pubnub = new PubNub(pnConfiguration);
/* Instantiate PubNub */
PNConfiguration *configuration = [PNConfiguration configurationWithPublishKey:@"myPublishKey" subscribeKey:@"mySubscribeKey"];
self.client = [PubNub clientWithConfiguration:configuration];
[self.client addListener:self];
/* Instantiate PubNub */
PNConfiguration pnConfiguration = new PNConfiguration();
pnConfiguration.PublishKey = "myPublishKey";
pnConfiguration.SubscribeKey = "mySubscribeKey";

Pubnub pubnub = new Pubnub(pnConfiguration);
/***************
For the 70+ SDKs that PubNub supports go to:
http://www.pubnub.com/docs
****************/

3

Enable Storage & Playback

Enable Storage & Playback on your keys in the Admin Console to use this feature.

4

Publish Messages

In order to store and replay messages from the stream, the stream first needs to be populated with messages. So we use the publish functionality to send messages to our demo_tutorial channel.

// Publish a message to the demo_tutorial channel
pubnub.publish(
    {
        message: {
            "color":"blue"
        },
        channel: 'demo_tutorial'
    },
    function(status, response){
        if (status.error) {
        // handle error
            console.log(status)
        } else {
            console.log("message Published w/ timetoken", response.timetoken)
        }
    }
);

/* Publish a message to the demo_tutorial channel */
JSONObject data = new JSONObject();

try {
    data.put("color", "blue");
} catch (JSONException e) {
    e.printStackTrace();
}

pubnub.publish()
    .message(data)
    .channel("demo_tutorial")
    .async(new PNCallback<PNPublishResult>() {
        @Override
        public void onResponse(PNPublishResult result, PNStatus status){

        }
    });
[self.client publish: @{@"color": @"blue"} toChannel: @"demo_tutorial"
      withCompletion:^(PNPublishStatus *status) {

    if (!status.isError) {

        // Message successfully published to specified channel.
    }
    else {

        /**
         Handle message publish error. Check 'category' property to find out possible reason because of which request did fail.
         Review 'errorData' property (which has PNErrorData data type) of status object to get additional information about issue.

         Request can be resent using: [status retry];
         */
    }
}];
/* Publish a simple message to the demo_tutorial channel */
Dictionary<string, string> data = new Dictionary<string, string>();

try {
    data.Add("color", "blue");
}
catch (Exception e) {
    Console.WriteLine(e.ToString());
}

pubnub.Publish()
    .Channel("demo_tutorial")
    .Message(data)
    .Async(new PNPublishResultExt((publishResult, publishStatus) => {
        if (publishStatus.Error) {
            Console.WriteLine("Error occured");
        }
    }));
/***************
For the 70+ SDKs that PubNub supports go to:
http://www.pubnub.com/docs
****************/

5

Call History

We can now ask for the last 100 messages on this channel using history.

// Detailed history of previously published messages
// Maximum records returned per request is = 100
pubnub.history(
    {
        channel : 'demo_tutorial',
        count : 100
    },
    function(status, response){
        console.log(response);
    }
);
/* Detailed history of previously published messages */
/* Maximum records returned per request is = 100 */
pubnub.history()
    .channel("demo_tutorial")
    .count(100)
    .async(new PNCallback<PNHistoryResult>() {
        @Override
        public void onResponse(PNHistoryResult result, PNStatus status) {
            System.out.println(result.getMessages());
        }
    });

/* Detailed history of previously published messages */
/* Maximum records returned per request is = 100 */
[self.client historyForChannel: @"demo_tutorial" start:nil end:nil limit:100
                withCompletion:^(PNHistoryResult *result, PNErrorStatus *status) {

    if (!status) {

        /**
         Handle downloaded history using:
            result.data.start - oldest message time stamp in response
            result.data.end - newest message time stamp in response
            result.data.messages - list of messages
         */
    }
    else {

        /**
         Handle message history download error. Check 'category' property to find out possible reason because of which request did fail.
         Review 'errorData' property (which has PNErrorData data type) of status object to get additional information about issue.

         Request can be resent using: [status retry];
         */
    }
}];
/* Detailed history of previously published messages */
/* Maximum records returned per request is = 100 */
pubnub.History()
    .Channel("demo_tutorial")
    .Count(100)
    .Async(new PNHistoryResultExt((result, status)=> {
        if (result != null) {
            Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(result.Messages));
        }
    }));
/***************
For the 70+ SDKs that PubNub supports go to:
http://www.pubnub.com/docs
****************/

6

Demo

In this demo, select any pattern of the color codes below. PubNub tracks the clicks and updates the console in realtime with your color selections. You can also choose how many events you want to pull in using the history() call and play that back in the same demo!

RED
BLUE
GREEN
YELLOW
Replay

7

Next Steps

Congratulations! With those few steps, you've successfully used Storage & Playback. Checkout Storage & Playback Tutorial to see what else can you do with it.

Sign Up for a free PubNub account if you haven't already.

Get coding right away using our 70+ SDKs in your favorite language, or build on top of one of our demo applications.

storage and playback

Try PubNub Today

Try Our APIs
  • 1M Transactions
  • 1GB Data Persistence
  • All major Features