Feedback

PubNub Publish/Subscribe Tutorial

Add Publish Subscribe to any app with PubNub Data Streams
PubNub Publish/Subscribe Tutorial

PubNub Publish/Subscribe Tutorial

PubNub utilizes a Publish/Subscribe model for realtime data streaming and device signaling which lets you establish and maintain persistent socket connections to any device and push data to global audiences in less than ¼ of a second.

You can publish messages to any given channel, and subscribing clients receive only messages associated with that channel. The message payload can be any JSON data including numbers, strings, arrays, and objects.

  • Chat rooms: Sending and receiving messages
  • Locations and Connected cars: dispatching taxi cabs
  • Smart sensors: Receiving data from a sensor for data visualizations
  • Health: Monitoring heart rate from a patient's wearable device
  • Multiplayer gamings
  • Interactive media: audience-participating voting system
  • And many many more...

To build an application that leverages the PubNub Data Stream, you need to sign up for your account to obtain API keys.

Once you have successfully signed up you will be taken to the admin page.

Admin Page

You can edit the app name by clicking the App name ("My First PubNub App") and on the next screen by clicking the pencil icon next to the App name.

You should have your Publish Key and Subscribe Key under your app. (You do not need the Secret Key for now. You will only need this when you are using Access Manager APIs).

You can add additional apps by clicking the APPS tab on the top menu bar, then clicking New App.

Create New App

You will get a new set of Publish and Subscribe Keys each time you create a new app.

To get started with PubNub JavaScript APIs, you need to include the latest (or desired) version of pubnub.js from CDN or locally.

<script src="https://cdn.pubnub.com/sdk/javascript/pubnub.4.x.x.min.js"></script>

You can find the latest version on the JavaScript SDK Getting Started page.

First things first: initialize a PubNub instance.

var pubnub = new PubNub({
    subscribeKey: 'your_sub_key', // always required
    publishKey: 'your_pub_key' // only required if publishing
});

Take a look at the Tic-Tac-Toe demo. This is a simple multi-player game using PubNub's pub/sub APIs.

Each time player X click one of the cells, the move is published to PubNub data stream. The opponent, player O receives the data by subscribing to the channel and receiving the message that was published. The game's user-interface on both browser windows is updated, as well as the game status is updated upon each subscribe call.

pubsub guide 3

When a player makes a move, publish the player name (either X or O) and the position that indicates the coordinate of row and column (e.g. 1-2, 3-3, etc.) :

pubnub.publish(
    {
        message: {
            player: 'X',
            position: '2-2'
        },
        channel: 'tic-tac-toe'
    },
    function (status, response) {
        if (status.error) {
            console.log(status)
        } else {
            console.log("message Published w/ timetoken", response.timetoken)
        }
    }
);

The callback is called when the operation is successful.

Channel names are UTF-8 compatible. Do not use any of the following characters:

  • comma: ,
  • slash: /
  • backslash: \
  • period: .
  • asterisks: *
  • colon: :

Also keep in mind that when you name the channel you want to keep it short enough not to take up the payload size. The maximum size of each message, including the channel name, is 32KB.

While you are playing the Tic-Tac-Toe demo, observe how each move is being published in the Publish/Subscribe Explained section on the bottom of the demo page.

All players subscribe to the channel get the published data from the stream, each time a player publishes their move.

In this scenario, the player X made a move (and the position is 2-2) and data is published to the channel, and right after the data is published, both X and O receive the data as they are subscribed to the channel.

The game status and the UI is updated on both ends, when the success callback is called:

pubnub.addListener({
    status: function(statusEvent) {
        if (statusEvent.category === "PNConnectedCategory") {
            play();
        } else if (statusEvent.category === "PNUnknownCategory") {
            var newState = {
                new: 'error'
            };
            pubnub.setState(
                {
                    state: newState 
                },
                function (status) {
                    console.log(statusEvent.errorData.message)
                }
            );
        } 
    },
    message: function(message) {
        checkGameStatus(message);
        updateUI(message);
    }
})

pubnub.subscribe({ 
    channels: ['tic-tac-toe'] 
});

There is an optional connect callback in the subscribe method- this is called the first time the connection to PubNub is established. In this scenario, the new game is being set up (defined in your play function) at the callback.

While you are playing the Tic-Tac-Toe demo, observe how each move is being subscribed at Publish/Subscribe Explained section on the bottom of the demo page.

Although this feature is not used in this Tic Tac Toe demo app, you can unsubscribe to stop receiving messages from a given channel if you wish:

pubnub.unsubscribe({
    channels: ['some_channel']
});
Tags: 
Publish & Subscribe

Try PubNub Today

Connect up to 100 devices for Free