The University of PubNub is a lecture series with hands-on code examples designed to get you started using the PubNub Data Stream Network and coding your realtime app. Taught by PubNub engineers and experts, these lectures are short, code-oriented, and designed for real-world use.

PubNub 100 Data Stream Basics

Get started with essential data streaming concepts and learn how to integrate them into your design.

PubNub 200 Intermediate Functionality

Coming soon! Take your data streaming skill set to the next level. We’ll tackle advanced realtime concepts, consider edge cases, and begin learning higher-level design patterns

PubNub 300 Advanced Data Stream Designs

Coming soon! For engineers and architects who are comfortable with realtime concepts and features. We will dive deep into advanced designs and best practices for exceptional realtime apps.
PubNub 100 > UP100 > Intro to UP
PubNub 100 > UP100 > PubNub Basics
PubNub 100 > UP101 > Introduction to Pub/Sub Messaging
PubNub 100 > UP101 > Setting up Pub/Sub Messaging
PubNub 100 > UP101 > Pub/Sub Demo
PubNub 100 > UP102 > Introduction to Access Manager
PubNub 100 > UP102 > Authentication and Authorization
PubNub 100 > UP102 > Access Manager Demo
PubNub 100 > UP103 > Introduction to Storage and Playback
PubNub 100 > UP103 > Storage & Playback Demo
PubNub 100 > UP104 > Introduction to Presence
PubNub 100 > UP104 > Streaming Events
PubNub 100 > UP104 > Non-Streaming Events
PubNub 100 > UP105 > Introduction to Stream Controller
PubNub 100 > UP105 > Multiplexing
PubNub 100 > UP105 > Multiplexing Demo
PubNub 100 > UP105 > Channel Groups
PubNub 100 > UP105 > Further Usage
PubNub 100 > UP105 > Channel Groups Demo
PubNub 100 > UP106 > Intro to Mobile Push
PubNub 100 > UP106 > Setting Up Mobile Push on PubNub
PubNub 100 > UP106 > Sending Mobile Push Notifications
PubNub 100 > UP106 > Wrap Up
PubNub 100 > UP107 > Overview of PubNub BLOCKS
PubNub 100 > UP107 > Enabling PubNub BLOCKS
PubNub 100 > UP107 > Creating a PubNub BLOCK
PubNub 100 > UP107 > BLOCKS Event Handler "Before Publish or Fire"
Transcript

1. Introduction to the University of PubNub

Welcome to the 100-level courses here at University of PubNub! This level is designed to work from the beginning to explain each piece of PubNub features, and how to use them.

Data Streaming

PubNub is a Data Stream Network. Okay, so what do we mean by streaming?

In typical HTTP-land, data sits on a server, and must be accessed via request. Data on the client-side is only updated when asked for.

In the world of “streaming”, you make a single request, and you receive data and events as they happen. While various open-source technologies allow you to stream data, only PubNub allows you to do so reliably, securely, and at global scale.

If you’re still shaky on how to to visualize Data Streaming, think about a stock market ticker. Any application keeping track of the stock market would have to update variables like price, volume, and market cap changes, all in realtime. In order to reach its destination efficiently and reliably, this data would need a stream.

Courses and Code

Each course in this level will cover all you need to know to use and begin implementing a single feature. Each course has several lessons, which step through code and concepts essential to to building an understanding.

When we go into code, we’ll primarily be looking at PubNub-related functions, rather than entire applications. We should note that, for simplicity’s sake, we’re teaching this course primarily with our Javascript SDK.

Sometimes, a particular feature might be implemented differently, depending on the SDK, so be sure to check our official documentation if you have questions. When applicable, specific links can also be found in the transcript below.

By the end of this level, you’ll come away with a well-rounded understanding of each piece of PubNub. Certain advanced features, or more complicated usage, is reserved for more detailed discussions at the next level of courses. Yet, the courses here will give you the tools you need to understand PubNub’s systems and start implementing each of our features into your app.

 

 

 

2. Getting Started with PubNub

Making an Account and Getting Your Keys

The first step to using PubNub is to make an account, in order to get your own set of keys. If you’re watching this video, chances are you’re already on pubnub.com. If so, click on the blue “Get Started” button on the top right-hand corner of your screen.

When you’re done, login, and you’ll be taken to the Admin Dashboard. Here you’ll find everything you need to start using PubNub. Before we dive into everything you see here, let’s back up and define some basic concepts.

PubNub Keys

Key Set

Your essential access point to PubNub services are your key sets. Each set includes a Subscribe Key, Publish Key, and Secret Key. Together, these keys define a single domain for two-way communication.

  • Subscribe Key: “LookUpID” for your account; namespace. Allows a device to receive data over a stream.
  • Publish Key: Allows a device to send data over a stream.
  • Secret Key: Only for signing grants/security (covered in AM)
  • Channels: Channels are two-way communication vectors, defined by a keyset and a channel name. It’s like a frequency on a two-way radio: those with access can use a single channel to both “listen” and “broadcast.”

Admin Dashboard

Add-Ons

Scrolling down, the section entitled “Features” allows you to activate additional services, such as Access Manager, Presence, Mobile Push Notifications, and more. With any PubNub account, you get Access Manager for free, but it is off by default. Throughout this level, we’ll cover the proper usage of each of these features.

Debug Console (What it’s for)

You should also see a link to our debug console. Here, you can input your keysets and channel names in order to test your implementation of PubNub.

SDK/Github Repos

PubNub supports 70+ SDKs, allowing you to easily use our technology anywhere. In essence, you’ll be using these to put PubNub into your app.

Docs: Depending on which SDK you use, specific methods may vary. Fortunately, we have extensive documentation that should help you, should you need a reference.

Administration Key Management Best Practices

We’re almost done with the overview. Just one last thing: In PubNub terms, what are Apps, and what are Keys? How are they related?

There’s a simple hierarchy:

    Account > Apps > Keys

  • Apps: We recommend you use “Apps” as the top-level organization for each different project you build using PubNub.
  • Keys: An unlimited number of Key-sets can be generated within an App. It’s important to remember that a given keyset runs an entire system, and is not used for individual users. Instead, you might use separate keys for different environments, such as development, testing, and production.

Okay. That’s all you need to know to understand what we’ll be doing in the following courses. Next time, we’ll be working on the core of PubNub: realtime, bi-directional Pub/Sub messaging. Stay tuned!

 

 

 

Introduction to Pub/Sub Messaging

The foundation of PubNub is providing you the ability to integrate scalable, realtime data streams into your applications. Using the publish/subscribe paradigm, subscribers to a particular channel will receive any and all messages that are published to that channel. It doesn’t matter if there is one subscriber, 10 subscribers, 1000 subscribers or millions of subscribers, a published message will be delivered to all of those subscribers on that channel in less than ¼ second1.

Basically, there are 3 phases of message delivery:

  1. Your app sends a request to PubNub to publish a message
  2. PubNub receives that publish request and sends that message to all currently connected subscribers
  3. The connected subscribers receive that message

Basic Elements of PubNub Publish and Subscribe

When it comes to using PubNub, there are three basic elements:

  • key set
  • channels
  • messages

Pub/Sub Key Set

Every PubNub operation requires that you initialize the PubNub object, and that you do so with at least a subscribe key. This will allow the device to receive PubNub messages, including those associated with add-on features. You only need to provide the publish key in the init if there is a need to publish messages. But, even if a client is only publishing messages, it still requires the subscribe key, too.

Channels:

Now that you understand what the publish and subscribe keys are and what they are used for, you need to understand the concept of a channel. Pretty simple, channels are how messages are sent and received. Clients that subscribe to a channel will receive messages that are published on that channel.

Channels are unique within a set of keys (the publish and subscribe keys). So channel blue for one set of pub/sub keys is not the same as a channel by the same name under a different key set. So you can’t publish a message on a channel under one key set and receive that message on that channel under another key set. To put it another way, a key set defines a namespace for channels.

Channels are very lightweight and flexible. If you are familiar with common message queue servers like RabbitMQ or ActiveMQ, you might know that you have to declare topics, subjects, and queues for channels before you use them, or you might have to initialize queues with certain properties to tailor how it works. With PubNub, channels exist merely by using them. Just publish or subscribe to a channel name and nothing more.

And, use as many channels as your app requires. There is no additional charge for the number of channels you use. But, you should use them in a way that makes the most sense for your use case. We will be discussing different use cases that leverage channels for different purposes.

And finally, a channel is just a channel. What you use it for is completely up to your application’s requirements. For example, a channel might be used for 1 to 1 private chat, many to many group chat, 1 to many broadcasting, or many to 1 fan-in data collection2. And a channel that is being used for private chat can suddenly be used for group chat. It is just up to you to allow more users to start subscribing and publishing to that channel. So channels are just blank communication devices for which you determine the actual usage.

PubNub Messages:

PubNub messages are packets of data that can contain any JSON serializable data, including: {Objects}[Arrays]Numbers – 1, 2, 3… and “Strings.” String content can include any UTF-8 character, single-byte and multi-byte. Our maximum size for any single message is 32KB.

The message doesn’t have to be formatted in JSON, but we recommend it, depending on which platform you’re on. It can be any object, as long as it’s serializable. Essentially, most people use JSON, and what is in that set of formatted data is up to you- those keys and values.

We’ll talk in other courses about special keys that are predefined to do special things, but for you, those keys and values can be whatever you need them to be.

1 This is an average latency expectation. Latency is not guaranteed as we do not control the last mile of connectivity.
2 Fan-in is an advanced design pattern that requires a robust, scalable server implementation which we will discuss in an advanced course.

 

 

 

Setting up Pub/Sub Messaging

Initialize the PubNub object

Let’s take a look at how Publish/Subscribe looks in code.

The first thing you need to do before performing any PubNub action is instantiate (initialize, create) the PubNub object:

var pubnub = PUBNUB({
    publish_key: "pub-key", 
    subscribe_key: "sub-key"
});

Here, you enter your Publish and Subscribe keys as arguments when creating the PubNub object. Later, as we cover more advanced features, we will discuss the additional, optional parameters that you can manipulate.

This object provides a means to publish, subscribe, get history, check presence and all the other functionality you might want to implement using PubNub APIs..

Subscribe to a Channel

Now that you have initialized a PubNub object, you can subscribe to a channel. All you have to do is provide the channel that you want to subscribe to, and a function for those messages to be received on when messages are published to that channel.

pubnub.subscribe({
    channel: "red", 
    message: function(msg){console.log(msg);}
});

Here, we’re simply printing the received message to our console. But, what you do with the message when it’s received in this callback function is up to you.

Publish to a Channel

So far you have written some code to listen (subscribe) to a channel. But nothing is going to happen unless someone actually publishes a message to that channel.

pubnub.publish({
    channel: "red", 
    message: "Hello there.", 
    success: function(msg){console.log(msg);}
});

To publish, all you need to do is specify your channel name, and the message you’re sending. You can’t publish to multiple channels at once. But, you can subscribe to multiple channels in a single call: simply enter your channels as a comma-delimited list under the property “channel,” and you’ll be listening on each one.

It’s crucial that you do NOT stringify your JSON. PubNub will always escape, and unescape, for you. Simply publish your data as-is, and we take care of the rest.

This message is a hard-coded string which does not make for a very interesting chat app. Obviously you would provide some UI elements (textbox and button) to allow a user to type the desired message and submit it. Again, a message may be up to 32Kb of any kind of JSON serializable data, opening our pub/sub service to a huge range of possible uses.

At its core, PubNub is conceptually easy to understand, as it revolves around the pub/sub messaging you’ve just learned. But, there’s more to learn! In a later, advanced course on PubNub, you’ll be able to learn more about optional parameters and additional pub/sub functionality.

In the next course on this level, we’ll start taking on some additional features, so that you can start working with PubNub in a more sophisticated way.

 

 

 

3. Implementing Publish/Subscribe Messaging

1. Introduction

Now we’re going to show you how to publish and subscribe with PubNub.

Our testing environment here is just two Chrome browser windows.One is set to incognito mode, so that there’s no process overlap between the two, simulating two separate users.

On the left is User 1, and on the right is User 2. Both will subscribe to the same channel and publish to that channel, using the same keyset.

For this test I’m just using a local HTML file that includes the Pubnub Library.

You can see the link to our CDN: http://cdn.pubnub.com/pubnub-dev.js

PN-Dev, used here, always points to the latest released version. For production, you’ll want to use a versioned CDN. Please refer to our docs for the proper CDN URLs.

Link: www.pubnub.com/docs/web-javascript/pubnub-javascript-sdk

For this demo, we’ll be adding code on the fly using Chrome’s console.

2. Step one: Initialization.

Our first step is to initialize PubNub. For this, you should use your own publish and subscribe keys.

‘Init’ is optional. Calling ‘var pubnub’ does same thing without it.

Enter the init call and your pub/sub keys in both browsers.

var pubnub = PUBNUB({
    subscribe_key: 'demo',
    publish_key: 'demo',
});

Now both users have PubNub objects initialized with the same keys.

3. Subscribe to Channels and Publish

Next up: subscribe to a channel. Both browsers will subscribe to channel “ch1.”

pubnub.subscribe({
    channel: 'ch1',
    message: function(m){console.log("Message received: " + JSON.stringify(m))}
});

Now, both browsers are ready to receive messages published over channel “ch1.”
Enter the subscribe method in both browsers, as seen here.

The message callback will log the published messages to the console.

JSON stringify, inside the callback, stringifies message so it isn’t output as a JSON object, for demo purposes.

Now that both users are subscribed to ch1, let’s publish a message using this call.

Below, you can see fields for the channel and the message. The keys and values in the message are completely up to you and based on your usecase. In this case, we’re imagining a sample chat-app.

// good publish – publish JSON object

pubnub.publish({
    channel: "ch1",
    message: {from: 'user_111', text: 'Hello there!'},
    success: function(m){console.log("Message received: " + JSON.stringify(m))},
    error: function(m){console.log("Message received: " + JSON.stringify(m))}
});

Both browsers will receive the message, because they’re both subscribed to channel “ch1.”

We talked about not stringifying your JSON when you publish, as PubNub does this for you. What happens if you stringify JSON before you publish?

// bad publish – shows publish stringified JSON issue

pubnub.publish({
    channel: 'ch1',
    message: JSON.stringify({from:'user_111', text:'Hello there!'}),
    success: function(m){console.log("Message received: " + JSON.stringify(m))},
    error: function(m){console.log("Message received: " + JSON.stringify(m))}
});

You’ll see that, when you receive the message, it has quotes around the entire thing, and backslashes throughout. In general, do not stringify your JSON before you publish it. Some SDKs will return errors, and in any case, you’ll end up doing more work.

That’s about it. If you publish a message from User 2, you’ll also see it appear in channel ch1 on both browsers.

4. Lifecycle Callbacks

When it comes to the subscribe method, there are additional callbacks that you can include: Connect, Disconnect, and Reconnect.These are connection lifecycle callbacks.

pubnub.subscribe({
    channel: 'ch1',
    message: function(m){console.log("Message received: " + JSON.stringify(m))},
    connect: function(m){console.log("Connected: " + JSON.stringify(m))},
    disconnect: function(m){console.log("Disconnect: " + JSON.stringify(m))},
    reconnect: function(m){console.log("Reconnected: ' + JSON.stringify(m))}
});

If there was a network connection issue, “Disconnect” would be called. When you get back online, “Reconnect” will be called. These are optional, but you’d want to implement these in a real application.

That’s about all there is for basic publish/subscribe messaging in PubNub.

 

 

 

Introduction to Access Manager Basics

What is Access Manager?

Access Manager allows developers to enforce secure access to channels in your PubNub application through the granting and revoking of permissions. When Access Manager is enabled, subscribe, publish and any other PubNub operation will require that access be granted first.

So how do we grant access to channels? There are a few players involved in this.

The essence of Access Manager is authorization, or permissions, to read or write to a given channel. This is done via an “authorization token” (or key), which validates a given set of permissions.

You can think of Access Manager as the bouncer at a concert, and the authorization token as a ticket. When you present your ticket to the bouncer, he will determine if you have permission to enter, and where you can go once inside. In a similar way, an auth token determines what channels a client device can subscribe and publish to.

It’s important to note that PubNub is only a part of the larger security picture. We are assuming you currently manage a database of registered users within your application. Authentication of these users (login with username/password) is the first step, and happens according to the system of your choice. Only once a user is authenticated will you pass in the auth key to grant access to the necessary channels that this user needs.

All About Auth Keys

Access to a resource is granted or denied via the “authorization token” (aka auth key) currently set on the client.

What is it? Well, whatever you want, really. Access Manager enables you to generate an arbitrary value for auth key using the method of your choice. This makes it possible to integrate a PubNub application with a pre-existing user authentication scheme or Security Authority.

 

 

 

Authentication and Authorization Overview

We mentioned this earlier, but let’s take a minute to survey the process of integrating Access Manager, and discuss Authorization vs Authentication.

Access Manager is just one piece of the overall security picture.

Authentication means making sure a user or device is who they say they are, typically by providing credentials like a username and password. PubNub, as a communication layer, has no inherent system set up for this. So, you will need to implement an authentication system on your server.

Luckily, because you can generate any value for the auth-key, it’s easy to integrate your chosen system with Access Manager. We recommend that, once a user is authenticated, your server generates their auth-key.

For the auth-key, we recommend a long, randomly-generated string, or the user’s session ID.

Once you’ve authenticated a user, you can begin the process to authorize channel access with Access Manager:

  • Your server initializes PubNub using your secret-key. This key should only be used on your server. Never expose your secret key on your client-side application.
  • The server grants read and/or write access to the necessary channels for this authenticated user, using the auth-key it just generated.
  • The Auth-key is returned to the client app, usually through the client’s own authentication mechanism.
  • Client app initializes their PubNub object using the auth-key
  • Because the server has already granted access to this client’s Auth key, this Client app can then subscribe or publish based on whatever access they’ve been granted.

 

 

 

Implementing Access Manager

That was a lot to take in. Let’s take a closer look and step through each stage.

Access Manager is a free, additional service that is turned off by default.
You can start using Access Manager by going to admin.pubnub.com and enabling the add-on.

presence basics

 

Do note that when you enable Access Manager on your PubNub keys, it takes effect immediately and all publish/subscribe operations will not go through unless they have proper authorization.

Server Operations

Initialize PubNub Instance with the Secret Key

You are already familiar with using the publish and subscribe keys to initialize your PubNub object. By including the secret key in the initialization you now have the ability to grant access. The secret key should only be used within a secure server, and not exposed to client devices.

To enable Access Manager, simply initialize PubNub with your Secret_Key.

PAM demo

 

We recommend performing the administrative operations on your server since you would not want your PubNub secret key to be distributed with your application.

Grant:

Grant is an API call to use Access Manager to grant permissions to client auth-keys. This would appear once you’ve authenticated a user and generated their auth-key. Here’s your Concert promoter telling the bouncer who’s allowed in. You have control of several properties:

  • read – boolean value for read permission (can be used for channels or channel groups)
  • write – boolean value for write permission (not applicable for channel groups)
  • channel channel to set the permission for
  • auth-key – Auth token that the client will specify while initializing the connection to PubNub. If left blank, the permission will be granted on the channel level.

*Presence: must grant read access to -pnpres channel

Here’s what a grant call looks like:

pubnub.grant({
    channel: 'my_channel',
    auth_key: 'my_rw_authkey',
    read: true,
    write: true,
    ttl: 5,
    callback: function(m){console.log(m)}
});

 

Client Operations

A client application uses Access Manager simply by initializing with the auth-key granted to them. This means that you’ll need some mechanism to pass the auth-key back to the client device from your user management server.

Initialize with auth key

By initializing with the auth-key, PubNub automatically appends it to any PubNub operation. If a key tries to perform an operation without proper permissions, the message is rejected.

Certain operations will be affected when Access Manager is enabled:

  • Subscribe – will need read permissions on channel
  • Publish – will need write permissions on channel
  • Presence – will need read permissions on the relevant “-pnpres” channel. If you don’t know what that means, check out course UP104.
  • History – will need read permissions on channel. History is covered more centrally in course UP103.
  • Push Notifications – will need write permissions on channel. See course UP107 for a basis in Push Notifications with PubNub.

Authorization and Authentication are linked, but decidedly different. We hope you have a sense for how, through Access Manager, you can control permissions on your PubNub channels. With more advanced, multi-feature implementations, it’s possible to do even more with security through PubNub. For now, you have enough to easily manage permissions on your channels.

 

 

 

Introduction to Storage and Playback

In this course, we’ll discuss PubNub’s Storage and Playback add-on.

What’s Storage and Playback for? Put simply, it allows you to store and retrieve messages sent over the PubNub network.

Why would you use Storage and Playback? For example, if you were using PubNub to power your chat app, Storage and Playback would allow you to populate your chat history when the app first loads.

Similarly, using Storage and Playback would allow you to receive messages missed because of a dropped connection, delivering them in sequence.

For Internet of Things or Home Automation devices, this feature can be used to enable automatic provisioning or updates on device startup, with no client-side configuration or action required.

Using this feature, you could also replay live events- crowd voting, score keeping, and more- by retrieving realtime data.

Enable Storage & Playback:

Enable Storage and Playback like any other add-on by going to the Admin Dashboard.

Published messages are received by the PubNub network and sent to subscribers. If Storage and Playback is enabled for your account, the message is also stored in the PubNub system for later retrieval.

As soon as Storage and Playback is enabled, all messages are stored automatically. You can configure how long messages are stored, up to a duration of forever.

Querying History

The crux of Storage and Playback is our History API. This API has two properties: Channel and Callback.
Channel: Where the messages are called from.
Callback: What you’ll do with the messages retrieved. What you place here will be similar to that placed in the callback of a typical subscribe call.

A simple history call looks like this:

pubnub.history({
channel: 'red' ,
Callback: function(m){console.log(m)},
});

Message Payloads:

Calling ‘history’ returns messages in an array of size 3, containing:

  • A list of messages.
  • The time-token of the first message.
  • The time-token of the last message.
[["message1", "message2", "message3",... ], "Start Time Token", "End Time Token"]]

Additional parameters:

Count:
The default number of returned messages is 100. This is also the maximum you can retrieve with a single call. A lower maximum can be set, but not higher. Getting more than 100 messages at a time requires a different design pattern that lets you page through history. We’ll cover that in-depth in a later course.

pubnub.history({
channel: 'red' ,
callback: function(m){console.log(JSON.stringify(m))},
count: 100 });

Start:
Provide a message’s time token. This returns all messages older than the time-token.
This changes the payload format to a dictionary, containing, for each item:

  • Message: the raw message.
  • A time token, associated with each message.
pubnub.history({
channel: 'red' ,
callback: function(m){console.log(JSON.stringify(m))},
start: 1421980851513004 });

End:
Provide a message’s time token. Gives you all messages from time specified and newer. Inclusive.

pubnub.history({
channel: 'red' ,
callback: function(m){console.log(JSON.stringify(m))},
end: 1421980851513004 });

Start and End:
Provide a value for both Start and End.
This will return up to 100 messages in the specified range.

pubnub.history({
channel: 'red' ,
callback: function(m){console.log(JSON.stringify(m))},
start: 1421980851513004 
end: 1421980851519999 });

Conclusion

It’s worth noting that storage and playback isn’t exactly a database. In the advanced course for this feature, we’ll explore some specific use cases, as well as some of the trickier functionality.

 

 

 

3. Implementing Storage and Playback (Demo)

Let’s show some examples of how to use the History API. We’ll need to initialize PubNub as always, here using the demo36 keys.

After we do that, we want to populate a channel on those keys with sample messages.

http://cdn.pubnub.com/pubnub-dev.js

var pubnub = PUBNUB({
    subscribe_key: 'demo',
    publish_key: 'demo',
});

Here’s how we’ll populate the channel. It’s a simple publish loop from 0-500, creating messages with the content message:index, from 0-499.

function pub() {
    for (var i = 0; i < 500; i++) {
        // publish 500 messages
        pubnub.publish({
            channel: 'up103_demo',
            message: 'message:' + i
        });
    }
}

Let’s do a simple history call with only the two required parameters: the channel (“up103_demo”) and a callback function. In this case, we’re outputting messages straight to the console, and we’re stringifying them so they’re easy to read.

pubnub.history({
    channel: 'up103_demo',
    callback: function(m){console.log(JSON.stringify(m))}
});

 

What we’re seeing as the output is that array of three elements:

  1. Up to 100 messages from message 400-499
  2. Time token of first message (msg 400)
  3. Time token of last message (msg 499)

Let’s add some parameters to narrow down the number of messages we receive. Let’s use the count parameter to return 5 messages as opposed to the default 100.

// count param

pubnub.history({
    channel: 'up103_demo',
    callback: function(m){console.log(JSON.stringify(m))},
    count: 5
});

 

As you can see, using count returns messages 495 through 499, and gives the first and last time tokens of this range, as you’d expect. We can make the count value 5, 10, all the way up to 100. Any number higher than 100 will not return more.

OK, let’s use the start parameter.

What I’ve done is, I’ve taken the publish time-token for message 495, and am providing it as the start parameter here.
The results may be surprising.

// start param – the tt value provided below should be replaced with the user’s own tt

pubnub.history({
    channel: 'up103_demo',
    callback: function(m){console.log(JSON.stringify(m))},
    start: 14437398701703382
});

 

I’m getting all the messages from that time token, and older. I got messages 394 through 494. I provided start for 495 and got all those before it, but not 495 itself.

Start is exclusive, meaning it returns all time tokens before the token declared, but not any messages with a time token matching that used in the start parameter itself. The rationale for this is related to an advanced design pattern, paging through history.

Let’s use that same time token and use it as an end parameter.

// end param – the tt value provided below should be replaced with the user’s own tt values

pubnub.history({
    channel: 'up103_demo',
    callback: function(m){console.log(JSON.stringify(m))},
    end: 14437398701703382
});

 

This time, we return messages 495 through 499. This time we did return the message connected to the time token we set as our parameter. End is inclusive.

What happens if we provide both start and end? We’ll use for our start value the time-token for message 495. For end, we’ll use the timetoken for message 498.

// start and end params – the tt values provided below should be replaced with the user’s own tt values

pubnub.history({
    channel: 'up103_demo',
    callback: function(m){console.log(JSON.stringify(m))},
    start: 14437398701703382,
    end: 14437398702285940
});

 

Our return is three messages: message 496 (start, using the time-token for 495, is still exclusive), and the end time token correlates to message 498.

In Summary, Storage and Playback stores all published messages and stores them, so you can retrieve them with the history API. We’ve gone over basic parameters, but there are other optional parameters and more advanced use cases that we’ll talk about in a later course.

 

 

 

University of PubNub: Presence Basics

Introduction to Presence

PubNub provides presence and state functionality which is built upon the publish & subscribe foundation making it easy to answer the question who’s online, and what are they doing? And being a global data stream network, PubNub will enable you to know when people come and go without repeated requests. The state provides data like name, age, online status (available, busy, typing, geo-location, etc.) enabling you to create rich user experience applications that leverage the actual participants of your application.

Getting started

As with other add-ons, you can enable Presence on your PubNub keys by visiting admin.pubnub.com and selecting the Presence add-on.

Presence Basics

We will cover the additional configuration values you can set for Presence later in the document.

Presence Basics

There are 4 types of events that the Presence API listens to and publishes:

  • Join – when a device subscribes to the channel
  • Leave – when a device unsubscribes from the channel
  • Timeout – when PubNub does not hear back from the device after a specified duration
  • State Change – when a device changes its state. This could be when a user is typing, a sensor is detecting a movement, or other activity. This will be covered in detail in a later course.

These events are published on a corresponding Presence channel. Presence channels are suffixed with a -pnpres. For example, if you subscribe to a channel called “PubNub”, the side Presence channel will be “PubNub-pnpres”. To receive presence events, you simply subscribe to this presence channel.

 

 

 

Streaming Events

Receiving Presence events is just like other realtime messaging over PubNub. For example, when a new user subscribes to a channel, the PubNub Network sends a join event (message) on behalf of that new subscriber. Any current subscribers on that channel that are also listening to presence events (implemented the presence callback) will receive that join event with data that identifies the new subscriber.

A presence event message contains:

  • Action – This can be any one of the 4 events (join, leave, timeout, state-change)
  • Timestamp – timestamp of event
  • UUID – The UUID of the device that generated the presence event
  • Occupancy – Current occupancy of the channel
  • Data – State data that is associated with that UUID (device)

As with other PubNub messages, streamed Presence events can be used and processed by your application.

UUID:

Each of the events described above are associated with an UUID (unique user identification). To ensure accurate Presence status across devices, you will need to include the UUID when you initialize your PubNub object.

Simply add a new property to your PubNub Initialization, like so:

var pubnub = PUBNUB({
     publish_key: 'demo',
     subscribe_key: 'demo',
     uuid: 'Stephen'
 });

PubNub also provides a function to generate UUIDs. You can store the generated UUID in local storage (browser cookie, shared preferences, etc) to use each time you initialize a PubNub object.

Presence callback:

Presence allows you to track when subscribers join and leave your channels, to see how many subscribers are currently connected, and to track state changes. Presence is closely associated with subscribing to a given channel.

When subscribing to a channel, you must also implement the presence callback if you want to listen to Presence events. This varies from one SDK to another, so you’ll want to check the documentation for your particular SDK.

In Javascript, the presence callback looks like this:

pubnub.subscribe({
    channel: "my_channel",
    presence: function(m){console.log(m)},
    callback: function(m){console.log(m)}
});

By listening to presence events to your main channel, the Presence API is also subscribing you to the sibling, -pnpres channel. Explicitly subscribing to this presence channel is reserved for a later discussion.

 

 

 

Non-Streaming Events

Presence Calls

While presence events like join and leave are received via long-running listener processes, some data can be retrieved on request when required in a short-lived request/response cycle.

For example, you may need to know who is currently subscribed to a channel right now. The here-now call will accomplish this requirement. This is typically something a new subscriber needs to populate a buddy list. From that point forward, new subscribers (buddies) can be added with each join event and removed with each leave event.

Here is a complete list of on-demand Presence calls:

  • Here Now:
    • Input: a channel name.
    • Output: a list of subscribers for a given channel.
pubnub.here_now({
    channel: "my_channel",
    callback: function(m){console.log(m)}
});

 

  • Where Now – Gets a list of channels that a given client is subscribed to.
    • Input: a UUID.
    • Output: a list of channels.
pubnub.where_now({
    uuid: "my_uuid",
    callback: function(m){console.log(m)}
    error: function(m){console.log(m)}
});

 

  • Global Here Now – Gets a list of every subscriber (by UUID) on every active channel associated with your keys.
pubnub.here_now({
    callback: function(m){console.log(m)}
});

 

  • Get State – Get the user state meta-data that a given client is subscribed to.
    • Input: a UUID.
    • Output: The current state associated with that UUID.
pubnub.state({
    channel: "my_channel",
    uuid: "my_uuid",
    callback: function(m){console.log(m)}
    error: function(m){console.log(m)}
});

 

Presence Configuration

You may want to fine-tune how Presence works with your account. There are currently two configurable parameters for Presence on your account. In your portal, you can configure these: “Presence Announce Max,” and “Presence Interval.”

You can adjust these, but the proper values really depend on your use case and architecture. We recommend that you email us for consultation and tuning of your Presence feature.

Conclusion

Using Presence in your application brings multi-user and multi-device environments to life, giving you (and your users) an easy way to visualize all the devices subscribing to a given channel.

 

 

 

Introduction to Stream Controller

PubNub’s data stream is well-suited to handle data at large volumes and fast speeds. Naturally, you may want to bring several data streams together into a single end-point. This is where Stream Controller comes in.

Essentially, it offers convenience for subscribers, vastly expanding your ability to listen to and manage significant numbers of channels.

Stream Controller expands the power of the subscriber by allowing you to receive messages on multiple channels from a single connection. This vastly extends one’s ability to connect to, and manage, large numbers of streams while keeping bandwidth costs to a minimum.

 

 

 

Multiplexing: One Connection, Multiple Channels

Stream Controller comes in two flavors. The first is called Channel Multiplexing. This enables developers to subscribe to 50 channels over a single TCP socket. On mobile devices, it is easy to realize the network bandwidth and battery power savings gained from channel multiplexing.

Subscribing to multiple channels is as simple as subscribing to a single channel. You can provide a comma delimited string list of channels all at once which all use the same callback for receiving messages, or you can subscribe to channels one at a time or in separate groups, each using the same or unique message receiving callbacks.

With standard multiplexing, the number of channels is limited to 50, but we recommend keeping the number of multiplexed channels to less than 10.

Here’s what it looks like when you use multiplexing to subscribe to multiple channels:

Subscribe to many channels in one subscribe call

//Subscribe to multiple channels using one subscribe call

pubnub.subscribe({
    channel: "blue,red,green",
    function(m){console.log(m);}
});

 

Subscribe to many channels across subsequent subscribe calls

// Subscribe to many channels over subsequent subscribe calls

pubnub.subscribe({
    channel: "apple,orange",
    callback: function(m){console.log(m);}
});

// more of your code goes here

// then subscribe to more channels later

pubnub.subscribe({
    channel: "peach,plum,cherry",
    callback: function(m){console.log(m);}
});

 

 

 

3. Implementing Multiplexing (Demo)

Ok, we’re going to show you how to use multiplexing.

I’ll do this by using two separate Chrome browser windows. On the left, we have our publisher, which is a tab in incognito mode This way, it’s separated on the process level, so we won’t have overlap between our simulated users.

On the right I have Chrome in regular mode. That will be the SUbscriber. In this demo we’ll publish from one, on the left, receive on the other as subscriber.

I’m starting with just a local HTML file that imports the PN library. I’ll first initialize each browser with the initialization code.

 

In the left browser, I’ll initialize PubNub with the UUID of user_111.

// left browser: init

var pubnub = PUBNUB({
    subscribe_key: 'demo',
    publish_key: 'demo',
    uuid: user_111
});

In the right-side browser, I’ll initialize with the UUID of user_222.

// right side browser

var pubnub = PUBNUB({
    subscribe_key: 'demo',
    publish_key: 'demo',
    uuid: user_222
});

 

Let’s make user_222 the subscriber and subscribe to some channels.

// right browser: subscribe to two channels

pubnub.subscribe({
    channel: 'ch1,ch2',
    message: function(m,e,c){console.log("Message: " + m + ", channel: " + c}
});

I’m subscribing to channels ch1 and ch2. My function takes in three parameters (message, envelope, and channel). My output, to the log, will be the message itself and the channel it came in on.

Back over to the publisher side, we’re just going to publish to channel ch1.

// left browser: publish to ch1

pubnub.publish({
    channel: 'ch1',
    message: 'Send a message on ch1!',
    success: function(m){console.log(m)},
    error: function(m){console.log(m)}
});

Sure enough, if we look back on the right, we got the right message on the right channel.

 

I’m subscribed to ch2 as well. Let’s publish a message in the same way, this time to ch2.

// left browser: publish to ch2

pubnub.publish({
channel: 'ch2',
    message: 'Send a message on ch2!',
    success: function(m){console.log(m)},
    error: function(m){console.log(m)}
});

Sure enough, the message arrives, and we see that it was sent over ch2.

 

Alright, so let’s shake it up a little bit. Let’s subscribe to a third channel but use a different callback.

// right browser: subscribe to ch3 with a different message callback

pubnub.subscribe({
    channel: 'ch3',
    message: function(m,e,c){console.log("Message received for ch3: " + m + ", channel: " + c}
});

So let’s publish to channel ch3 from the left browser.

// left browser: publish to ch3

pubnub.publish({
    channel: 'ch3',
    message: 'Send a message on ch3!',
    success: function(m){console.log(m)},
    error: function(m){console.log(m)}
});

 

So, how do you know what channels you’re subscribed to?

If you’ve seen the Presence course (UP104) you know the where_now and here_now calls. Let’s use where_now to see a list of our currently subscribed-to channels.

// right browser: where_now call

pubnub.where_now({
    callback: function(m){console.log(JSON.stringify(m)},
    error: function(m){console.log(m)}
});

As you’d expect, it shows that we’re subscribed to channels ch1, ch2, and ch3.

If we want, we can unsubscribe from one. Let’s unsubscribe from ch2- we don’t even need a callback. You could even unsub from a list of channels.

// right browser: unsubcribe from ch2

pubnub.unsubscribe({channel: 'ch2'});

 

When we test it from the left browser by publishing to ch2, we see no message received on the right browser. Sure enough, if we run another here_now call, we see channels ch1 and ch3, but not ch2.

 

 

 

Channel Groups

Channel groups take multiplexing to the next level by providing a more elegant mechanism for centrally managing the channels you subscribe to, and provides much larger channel limits. With standard multiplexing, the number of channels is limited to 50, but we recommend keeping the number of multiplexed channels to less than 10. If you will be more commonly supporting greater than 10 channel subscriptions per client connection, you should strongly consider using channel groups.

Channel Groups are, simply, groups of channels that can all be subscribed to with a single call.
The channel limit per channel group is 2000, and each client connection can subscribe to 10 total channel groups for a total of 20,000 channels! Now, this may not be the most common requirement, but it is useful for the Facebook or Twitter design patterns (friends & followers). You can imagine a channel group with the private channel of each of your friends or the users you follow so that you receive all the messages published by them.

Channel Groups cannot be subscribed to if empty, so let’s look at how to add channels to a group.

Adding Channels to a Channel Group

pubnub.channel_group_add_channel({
    callback: function(m){console.log(m);},
    error: function(e){console.log(e);},
    channel_group: "friends",
    channel: "rob,mohan,fred"
});

 

The callback parameter is not the where messages are received. This callback is merely for the acknowledgement from the server that the channels were successfully added to the group.

The callback looks like this:

{status: 200, message: "OK", service: "channel-registry", error: false}

As with channel names, each channel group and associated channel(s) is identified by a unique name. These names may be a string of up to 64 Unicode characters, excluding reserved characters: , , : , . , / , *, non-printable ASCII control characters and Unicode zero.

It does not matter if the channel group previously existed or not. Adding channels to a channel group creates the channel group. The same goes for channels. Merely subscribing or publishing to a channel summons it into existence. So, a channel group and all of its member channels may be created in a single call.

And if there were channels that were previously added to the channel group, then those channels will continue to be in that channel group.

Subscribe to a Channel Group

You subscribe to a channel group just like you subscribe to a channel. The only difference is the parameter name, and that fact that you now just add channels to the channel group. By doing so, you are subscribed to those channels.

Note: you can ONLY subscribe to channel groups; you cannot publish to one.

As a reminder, you cannot subscribe to an empty channel group. Without channels, a channel group cannot exist. So, when you set up your application logic to subscribe to a channel group, make sure you first add channels to that group before devices subscribe.

pubnub.subscribe({
    callback: function(msg){console.log(msg);},
    error: function(msg){console.log(msg);},
    channel_group: "friends",
});

At this point, you are subscribed to the channel group and are able to start receiving messages from any and all channels in that channel group. Whenever another channel is added to the channel group, you are immediately subscribed to that channel as well:

pubnub.channel_group_add_channel({
    callback: function(m){console.log(m);},
    error: function(e){console.log(e);},
    channel_group: "friends",
    channel: "charlotte"
});

 

So, all in all, there are four basic steps to keep in mind when using Channel Groups:

1.Create a channel group.

2.Add channels to the group.

3.Subscribe.

4.Continue to add/remove channels as application dictates.

 

 

 

Additional Usage:

Once you’ve subscribed to a channel group, there are a few other ways to use channel groups, and to manipulate channels for your users.

Channel Group Management

Remove Channels from a Group:
You can remove channels from a group. This effectively unsubscribes any subscribers from that channel. To do this, you’d use this call:

pubnub.channel_group_remove_channel({
    callback: function(m){console.log(m);},
    error: function(e){console.log(e);},
    channel_group: "friends",
    channel: "alex"
});

List all the channels in a channel group:

pubnub.channel_group_list_channels({
    channel_group: channelGroup,
    callback: displayCallback,
    error: displayCallback
});

Unsubscribe from a Channel Group:

pubnub.unsubscribe({
    callback: function(msg){console.log(msg);},
    error: function(msg){console.log(msg);},
    channel_group: "friends"
});

 

Multiple Subscribers to a Channel Group

As with single channels, channel groups can have multiple subscribers. You can create, for example, a shared channel group called sports that represents all of the sports channels: lacrosse, football, soccer, basketball. Anyone that subscribes to the sports channel group will instantly be subscribed to all of the channels in that group. There’s no need to subscribe to each channel of that channel group explicitly for every end user.

And even better, your server manages the channels that are in a channel group. This is where you can automate and securely control which channels each end user is ultimately subscribed to. If a new sports channel is added to your service’s portfolio, you can just add it to the sports channel group from your server. All end users subscribed to that channel group will now get messages for that newly added sports channel.

Custom Channel Groups

This is an example of shared, or custom channel groups, but each user could have one or more channel groups that are specific to just them – custom channel groups. This could be anything from a friends’ list to a stock portfolio.

e.g.
Channel group, “tech_stocks” that contains “AAPL”, “GOOG”, etc common stocks
vs.
Channel group, “eric1234_stocks” that contains the symbols of his choice

Again, there is nothing that makes a channel group custom or not, except for your application logic. In other words, there is no special attribute of a channel that you set as custom.

All channel groups (and channels) are treated equally in the eyes of the PubNub Network. Which clients subscribe to them is completely up to your application logic. Using Access Manager to restrict unauthorized access is a highly recommended practice, but this, and other advanced functionality, will be covered in a later course.

Conclusion

Stream Controller is the best way to subscribe to multiple channels at once. Not only is it easier to use, but it also offers greater efficiency whether you’re handling hundreds or thousands of channels. In the advanced course on this subject, we’ll cover some integrations of Stream Controller with other PubNub services. See you next time.

 

 

 

6. Implementing Channel Groups

Channel Groups

Ok. So, we are going to subscribe now using channel groups instead of multiplexing, and we’ll compare and contrast how the two features work. Channel Groups are more powerful and flexible in what you can do.

Our local HTML file grabs the PubNub javascript library:
http://cdn.pubnub.com/pubnub-dev.js

We’ll use the same setup as before. We have our publisher (user-111) on the left:

// left browser: init

var pubnub = PUBNUB({
    subscribe_key: 'demo',
    publish_key: 'demo',
    uuid: user_111
});

And we have our subscriber (user-222) on the right:

// right side browser

var pubnub = PUBNUB({
    subscribe_key: 'demo',
    publish_key: 'demo',
    uuid: user_222
});

 

This time, instead of subscribing to channel groups, our user_222 will subscribe to a channel group with channels already in it. The channel group will contain a list of channels. By subscribing to channel groups, you’re then subscribing to all channels within it.

So let’s have the publisher add a couple channels to the channel group first:

// left browser: add channels to channel group

pubnub.channnel_group_add_channel({
    callback: function(m){console.log(JSON.stringify(m))},
    channel_group: 'cg1',
    channel: 'ch1,ch2'
});

 

We have a callback to confirm the channels are added, the name of our channel group, and a list of the channels we want to add. It can be one or more channels here.

We subscribe here to channels ch1 and ch2 and we get the feedback that it worked.

 

Now on the subscriber side, we’re going to subscribe to that channel group, cg1, which means we’ll be subscribed to the channels in that group: ch1 and ch2.

// right browser: subscribe to channel group with two channels

pubnub.subscribe({
    channel_group: 'cg1',
    message: function(m,e,cg,l,ch){
    console.log("Message: " + m + ", channel group: " + cg + ", channel: " + ch)}
});

 

It’s a simple subscribe call, but instead of channel we designate channel group, provide the name of that group (cg1), and our callback has some different parameters this time.

The parameters I’ve given are:

m: The message itself

e: Envelope

cg: Channel Group

l: Latency

ch: Name of the Channel it’s published over

Why do I need a ‘cg’ parameter? Because channel groups work like channels: you can subscribe to different channel groups, and each can have different channels within it. This helps us see where data is coming form.

We’ll use parameters ‘cg’ and ‘ch’ to print out which channel group and channel the message came in on.

Alright, we’re subscribed to cg1. Back to our publisher, we’ll publish a message to one of the channels in that group.

We’re going to publish a message to ch1:

// left browser: publish message to ch1

pubnub.publish({
    channel: 'ch1',
    message: 'Send a message on ch1!',
    success: function(m){console.log("Message received: " + JSON.stringify(m))},
    error: function(m){console.log("Message received: " + JSON.stringify(m))}
});

 

We receive the message and see it was sent through group cg1, over channel ch1.

Now we’ll publish to ch2:

// left browser: publish message to ch2

pubnub.publish({
    channel: 'ch2',
    message: 'Send a message on ch2!',
    success: function(m){console.log(m)},
    error: function(m){console.log(m)}
});

 

We see the expected result. The message arrives through group cg1, over channel ch2.

We can also add channels to the channel group from our subscriber. Let’s add another channel to the channel group.

// right browser: add ch3 to channel group

pubnub.channnel_group_add_channel({
    callback: function(m){console.log(JSON.stringify(m))},
    channel_group: 'cg1',
    channel: 'ch3'
});

 

Again, we’ll add a channel to cg1, this time called “ch3.” We can test it with a simple publish.

// right browser: publish message to ch3

pubnub.publish({
    channel: 'ch3',
    message: 'Send a message on ch3!',
    success: function(m){console.log(m)},
    error: function(m){console.log(m)}
});

 

 

Ok, so you may have to do maintenance on a channel group.You may want to list out the channels in a group, or you might want a list of channels a given user is involved in. With channel groups, we can list channels with a simple call.

// right browser: list channels

pubnub.channnel_group_list_channels({
    channel_group: 'cg1',
    callback: function(m){console.log(JSON.stringify(m))}
});

In our console, we see that cg1 does indeed include ch1, ch2, ch3, and ch4 (from an earlier session). We see that these are all in our channel group, cg1.

 

Just as you can add channels to a group, you can remove channels. Let’s remove the channels from the publisher side- which might be your server.

If you think about the power of channel groups, your clients don’t actually have to subscribe or unsubscribe to channels themselves. You can have your server maintain the list of their subscriptions, simply by maintaining channels in channel groups they’re subscribed to.

Those channel groups can be common or limited to single users, fitting different use cases.

So let’s remove a channel with the remove_channels call. We’re going to remove ‘ch1’ from cg1.

// left browser: remove channels

pubnub.channnel_group_remove_channels({
    channel_group: 'cg1',
    channel: 'ch1',
    callback: function(m){console.log(JSON.stringify(m))}
});

 

If we list our channels again from the subscriber side, we can see that only ch2, ch3, and ch4 are left in the channel group.

So, in short, Instead of directly subscribing to channels, you can use cg to maintain the list of channels that any user is subscribed to in a much more flexible, easily maintained manner.

 

 

 

Intro to PubNub Mobile Push Notifications

Many are often confused about the difference between a PubNub realtime messages and mobile push notifications.

Why would you use mobile push notifications when you’re already using PubNub?

Mobile Push Notifications are usually used to notify a user of application updates in realtime, even if that application works on a traditional request-response model. Ideally, a PubNub application would allow you to see changes as they happen, but mobile has certain constraints.

iOS devices, for example, do not run in the background without permissions granted by Apple. With Android, unless you configure and implement your app to run as a background service, you may encounter similar challenges. The PubNub Mobile Push Gateway address this scenario.

What are Mobile Push Notifications, and how do you use the PubNub Mobile Push Gateway?

Mobile Push Notifications allow you to alert your mobile clients even if your app is running in the background but this is not as close to realtime as PubNub.

Push Notifications work in a similar fashion to regular Pub/Sub messaging. Sending a push notification is simply a matter of modifying your PubNub Publishes with special formatting, as well as setting up Push Notifications with your targeted mobile platform. Receiving them requires a subscribe call.

 

 

 

Setting up Mobile Push Notifications through PubNub

The eventual subscribe call is similar to subscribing to realtime message delivery, but there’s some extra setup.

At a high level, there are 4 basic tasks:

  • PubNub Key configuration
  • Obtaining registration or device token from the push service (APNS or GCM)
  • Registering the device with PubNub channels on which to receive push notifications
  • Implement the appropriate code to receive and process those push notifications

Enable Push Notifications

  • Enable Add-on at admin.pubnub.com
  • In the feature configuration, upload Cert (iOS)+ Server API key (Android)
  • That’s it!

Presence Basics
APNS PEM Cert

 

Register for Push Notifications with APNS or GCM

Next step is, you need to obtain a device registration token or ID for whichever platform(s) you plan to send notifications on.

The details on how to do this are outside of the PubNub domain, but the details are laid out in our documentation for each of our SDKs. You can register device tokens from the server or the client side.

Here’s the link to our Docs for retrieving device ID using JavaScript.

Register your device (PubNub channel specific registration)

  • We’ll have to register our device on a channel. When a message is published on that channel, the device will be able to receive a push notification.
pubnub.enablePushNotificationsOnChannel (channel, token, new Callback() {
@Override
public void successCallback (String channnel, Object message) {
Log.i(TAG, "GCM Add : " + message);
} 
@Override 
public void errorCallback(String channel, PubnubError error){
Log.e(TAG, "GCM Add : " + error);
}
});

In this case:

  • Channel: a PubNub channel
  • Token: Registration ID from Google

Now the device is registered both on mobile networks (APS, GCM) and PubNub.
This device will now get a Push Notification when a message is published on that channel.

Android – Receiving Push Notifications from Google

Now that the device can receive push notifications, it has to be set up to process and display them.

  • Create a class that extends GcmListenerService
  • Override the “onMessageReceived” method and implement your logic to deal with the Push Notification
  • Start the GCM Listener by adding the following code to your Android Manifest file:






When does the mobile device receive realtime messages vs. mobile push notifications?

When a mobile app is not active (suspended in the background or not running at all) then the device will receive only mobile push notifications that the device is registered to receive.

When a mobile app is active (running in the foreground) and subscribed to a channel for both realtime messages and push notifications, then it will receive both messages. Simply use the mobile OS’s API to receive the mobile push notification and ignore it (don’t display it). For example, on iOS the API is didReceiveRemoteNotification (Android has a similar API).

 

 

 

Sending Push Notifications

How is publishing realtime messages different from sending mobile push notifications?

There is no inherent difference – just use the publish API for the SDK you are using.

What data is sent to the realtime channel vs. what is sent to the push notification services?

Data can be provided in a single message payload that targets different gateways.

Provide the content in the message payload that is specific for each gateway: realtime, APNS & GCM (see sample payload format below).

Sending a push notification

Formatting the message payload to target realtime message delivery as well as mobile push notification delivery with one publish:

Dictionary objects sent to APNS and GCM mobile services must be in a well-formed format in order for the remote service (operated by Apple, Google, etc) to process.

For example, when sending native APNS and GCM alerts to Apple and Google via PubNub, you could send in this format:

{
"pn_apns": {
     "aps": {
"alert": "Your order is ready for pickup!"
}
},
"pn_gcm": {
"data":"This is data for only GCM devices"
},
"data_for_all": {
"info": "This is data all non-APNS and non-GCN devices would receive. They would also receive the pn_apns and pn_GCM data. "
}
}

When the above message is published:

APNS gateway enabled devices will only receive the data contained from within the pn_apns key (up to 2K characters).

AGCM gateway enabled devices will only receive the data contained from within the pn_gcm key (up to 4K characters).

ANon-APNS/GCM devices will receive the entire message payload, including the push gateway keys/values (up to 32K character including the APNS and GCM data).

As noted above, the value of the APNS object (contained within the pn_apns key) contains an object that will be forwarded in whole to the APNS gateway.

Note that it has one mandatory key: aps. Within the aps object, it has other non-mandatory fields, which include alert and badge, as well as some additional user-info/metadata fields contained within the payment_info key: credit_card and expiration.

 

 

 

Conclusion

Channel Debug

Before we sign off, there’s one last API call that might be useful for you.
In your message payload, you can include the line:

PN_Debug = true

This will publish high-level error messages to a debug channel. The name of this channel will use your original channel name, adding “-pndebug” as a suffix.

Example: If you publish messages on a channel “chat” with PN_Debug set to true, you’ll receive error messages on the channel “chat-pndebug.”

Wrap-Up

In conclusion, PubNub allows you to use push notifications when a connection to PubNub is unavailable, whether due to the app running in the background or mobile connectivity issues.

Implementing Push Notifications requires four steps:

  1. Enable the add-on and configure keys
  2. Obtain a registration ID or Device Token
  3. Register for Push Notifications on specific channels
  4. Implement code to receive and process Push Notifications

Sending push notifications is easy. Once push notifications are enabled on your key, simply format your published messages with fields to contain data for APNS, GCM, or MPNS (whichever are relevant to your application). This will allow these services to deliver push notifications to your mobile clients.

 

 

 

This lesson is the starting point for understanding what, why and how of PubNub BLOCKS. In this lecture style lesson, we cover the fundamental terminology and concepts of PubNub BLOCKS. This lesson lays the foundation for future lessons within the Introduction to BLOCKS course.

In this lesson, we cover how to enable PubNub BLOCKS on a keyset and finish with a small overview of the BLOCKS environment.

In this lesson, we pick up from the BLOCKS landing page and create a simple Event Handler while introducing the PubNub BLOCKS IDE and high-level coding concepts.

In this lesson, we focus on the code to implement an EventHandler of type Before Publish or Fire to manipulate messages of your dataStream prior to subscribers receiving that data. At the end of this lesson, you will have a working Hello World block.

  • PubNub 100
  • PubNub 200
  • PubNub 300
UP100: Intro
What PubNub, and UP, are all about.
Intro to UP PubNub Basics
UP101: Pub/Sub
Send data in the blink of an eye. Learn how to use our basic API, including initialization, publish and subscribe calls, and channels.
Introduction to Pub/Sub Messaging Setting up Pub/Sub Messaging Pub/Sub Demo
UP102: Access Manager
Learn how to integrate our authorization feature to control how clients access and use your data streams.
Introduction to Access Manager Authentication and Authorization Access Manager Demo
UP103: Storage and Playback
Total recall. Learn how to use our History API to retrieve past messages.
Introduction to Storage and Playback Storage & Playback Demo
UP104: Presence
Presence offers the ability to track clients on your streams. Learn to use presence events to improve your UX and produce new functionality from your channels.
Introduction to Presence Streaming Events Non-Streaming Events
UP105: Stream Controller
In this course, learn about multi-channel subscription, including best practices for multiplexing and channel groups.
Introduction to Stream Controller Multiplexing Multiplexing Demo Channel Groups Further Usage Channel Groups Demo
UP106: Mobile Push
See how to set up push notifications for your Pubnub keys, and learn best practices for sending and receiving notifications to multiple networks.
Intro to Mobile Push Setting Up Mobile Push on PubNub Sending Mobile Push Notifications Wrap Up
UP107: Overview of PubNub BLOCKS
This lesson is the starting point for understanding what, why and how of PubNub BLOCKS. In this lecture style lesson, we cover the fundamental terminology and concepts of PubNub BLOCKS. This lesson lays the foundation for future lessons within the Introduction to BLOCKS course.
Overview of PubNub BLOCKS Enabling PubNub BLOCKS Creating a PubNub BLOCK BLOCKS Event Handler "Before Publish or Fire"

Start Learning Today

PubNub University classes include a free account