Store realtime message streams for future retrieval and playback

Storage and Playback Getting Started Guide

Store realtime message streams for future retrieval and playback in a few steps with PubNub Storage & Playback

Storage and Playback Getting Started Guide

1

Install PubNub

To start publishing and subscribing, we first need to access our PubNub libraries. Include the code hosted on our CDN just before closing your HTML </body> tag.

Now you can instantiate a PubNub object using your own publish and subscribe keys or use our demo keys.

You will also need to enable Storage and Playback in your PubNub Admin Portal

/* View the Full Documentation. */
/* Instantiate PubNub */
PNConfiguration pnConfiguration = new PNConfiguration();
pnConfiguration.setPublishKey("Your Publish Key Here");
pnConfiguration.setSubscribeKey("Your Subscribe Key Here");

PubNub pubnub = new PubNub(pnConfiguration);
/* View the Full Documentation. */
/* Instantiate PubNub */
PNConfiguration *configuration = [PNConfiguration configurationWithPublishKey:@"Your publish key"

subscribeKey:@"Your subscribe key"];
self.client = [PubNub clientWithConfiguration:configuration];
[self.client addListener:self];
<!-- View the Full Documentation. -->
<!-- Include the PubNub Library -->
<script src="https://cdn.pubnub.com/sdk/javascript/pubnub.[version number].js"></script>

<!-- Instantiate PubNub -->
<script type="text/javascript">

    var pubnubDemo = new PubNub({
        publishKey: 'Your Publish Key Here',
        subscribeKey: 'Your Subscribe Key Here'
    });

</script>
/* View the Full Documentation. */
/* Instantiate PubNub */
PNConfiguration pnConfiguration = new PNConfiguration();
pnConfiguration.PublishKey = "Your Publish Key Here";
pnConfiguration.SubscribeKey = "Your Subscribe Key Here";

Pubnub pubnub = new Pubnub(pnConfiguration);
/***************
For all other languages,
check out the 70+ SDKs that PubNub supports
on our documentation page:
http://www.pubnub.com/docs
****************/

2

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 */
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 message to the demo_tutorial channel
pubnubDemo.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 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 all other languages,
check out the 70+ SDKs that PubNub supports
on our documentation page:
http://www.pubnub.com/docs
****************/

3

Call History

As long as the Storage and Playback feature is enabled for your account, 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)
    .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
pubnubDemo.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 PNHistoryResultExt((result, status)=> {
        if (result != null) {
            Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(result.Messages));
        }
    }));
/***************
For all other languages,
check out the 70+ SDKs that PubNub supports
on our documentation page:
http://www.pubnub.com/docs
****************/

4

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

5

You are now a master of Storage & Playback!

With those few steps, you've built your first PubNub application with Storage and Playback!

If you haven't already, Sign Up for a free PubNub account. Then continue with our other feature guides for Presence and Access Manager to make your app more robust.

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

logos
storage and playback