PubNub Presence Tutorial

Track online and offline status of users and devices
PubNub Presence Tutorial

PubNub Presence Tutorial

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.

  • Chat rooms: Showing users' online status
  • Collaborative Word doc: Showing who is typing
  • Smart sensors: Showing how many devices are connected
  • Multiplayer gamings: Showing all players names and stats
  • Interactive media: audience-participating voting system
  • Notifying when a user has joined or left a channel
  • Displaying who, and how many, users are subscribed to a particular channel
  • Showing which channel(s) an individual user is subscribed to
  • Showing associated state information for these users (location, typing status, etc)

To use the add-on feature, you need to enable Presence for your key in the Admin Dashboard.

Enable Presence Add-on

You can choose additional configuration values at the configuration modal dialog. You can always come back to your admin dashboard to modify the settings later.

Presence Add-on Configuration

Before proceeding, be sure you have completed the Pub & Sub tutorial first.

You can take a look at the Tic Tac Toe demo for Presence that explains how the APIs work, along with this documentation.

There are 3 types of default online status events that the Presence API listens to and publishes:

  • Join - when a user or device subscribes to the channel
  • Leave - when a user or device unsubscribes from the channel
  • Timeout - when PubNub does not hear back from the device after a specified duration

First, you need to initialize your connection to PubNub with a Unique User ID (UUID):

var pubnub = new PubNub({
    subscribeKey: 'your_sub_key',
    publishKey: 'your_pub_key',
    uuid: 'user-1234'
});

Once a UUID is set, you can enable presence events along with the subscribe call. You can also retrieve several event messages at the presence callback:

pubnub.addListener({
    presence: function(presenceEvent) {
        console.log(presenceEvent.action) // online status events
        console.log(presenceEvent.timestamp) // timestamp on the event is occurred
        console.log(presenceEvent.uuid) // uuid of the user
        console.log(presenceEvent.occupancy) // current number of users online
    }
})
 
pubnub.subscribe({ 
    channels: ['tic-tac-toe'],
    withPresence: true
});

Let's see how the presence works on the Tic-Tac-Toe demo.

Notice the number of players is displayed at the left hand side of the Tic Tac Toe board.

Additionally, when you don't have an another player, you get the message, "Waiting for your opponent…" at the right hand side. If more than two people are joining to the same game, whoever joined after the 2nd player gets an alert message so they cannot play the game. This feature is done by using the Presence API.

At the Presence API Explained section of the demo, you can live-view the "console" as a new event is triggered. Watch it while trying to join into the game from an another browser window or a tab, then kill the browser window/tab to trigger the timeout event.

You can also manually "leave" by unsubscribing from the game. (See the Quit button on the demo page).

Additionally, there is an another status event: state-change

  • state-change - when a custom value is modified

You can define custom state attributes, which can be any arbitrary data object. The state-change event is triggered when any of the values are modified.

For example, let’s say you are developing a chat app, and when you define the custom data to track if a user is currently typing:

{
    isTyping: false
}

The value changes to true as soon as the user starts pressing any alphanumeric keys.

You can set the state, using setState method:

pubnub.setState(
    {
        state: {
            isTyping: true
        },
        channels: ["awesome-chat"]
    },
    function (status, response) {
        // handle status, response
    }
);

When the data change is detected, state-change event is fired at the presence callback with subscribe:

pubnub.addListener({
    presence: function(presenceEvent) {  
        if(presenceEvent.action === 'state-change') {
            if(presenceEvent.data.isTyping === true) {
                dom.textContent = presenceEvent.uuid + ' is typing...';
            }      
        }
    }
})
 
pubnub.subscribe({ 
    channels: ['awesome-chat'],
    withPresence: true 
});

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 subscribed to a channel right now.

  • Here Now - Gets a list of subscribers for a given channel
  • Where Now - Gets a list of channels that a given client is subscribed to
  • Global Here Now - Gets a list of every subscriber (by UUID) on every active channel associated with your keys.
  • Get State - Get the user state meta-data that a given client is subscribed to

To get a list of "who is here now" for a given channel, use the hereNow() method:

pubnub.hereNow(
    {
        channels: ["awesome-chat"]
    }, 
    function (status, response) {
        // handle status, response
    }
);

To get a list of "which channel(s) is this UUID on right now", use the whereNow() method:

pubnub.whereNow(
    {
        uuid: "user-666"
    },
    function (status, response) {
        // handle status, response
    }
);

Timeout events are triggered when the server does not hear a heartbeat from the client within a default timeout time of 280 seconds.

This default timeout time can be adjusted, as well as the frequency in which the client sends heartbeats to the server. You can configure them at initialization:

var pubnub = new PubNub({
    subscribeKey: 'your_sub_key',
    publishKey: 'your_pub_key',
    uuid: 'user-1234'
});

By default, the heartbeat interval is set heartbeat/2 -1. When you manually set the heartbeat to 120 seconds, the client will send a heartbeat "ping" every 59 (= 120 / 2 -1) seconds.

Also, you can override the heartbeat interval if you wish:

var pubnub = new PubNub({
    subscribeKey: 'your_sub_key',
    publishKey: 'your_pub_key',
    uuid: 'user-1234',
    heartbeatInterval: 30 // the frequency of ping from client to server
});

In the above example, the server knows to emit a timeout event if it does not receive a ping from it within 120s. The device will ping back from the client to the server to tell it is alive every 30s.

You should be careful with the network connection types and conditions. Also keep in mind more frequent ping means more battery consumption, especially on mobile devices.

Tags: 
Presence

Try PubNub Today

Connect up to 100 devices for Free