PubNub Publish/Subscribe Tutorial

Add Publish Subscribe to any app with PubNub Data Streams

Demo URL:

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, create an account and obtain your publish/subscribe API keys:

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=""></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.) :

        message: {
            player: 'X',
            position: '2-2'
        channel: 'tic-tac-toe'
    function (status, response) {
        if (status.error) {
        } 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:

    status: function(statusEvent) {
        if (statusEvent.category === "PNConnectedCategory") {
        } else if (statusEvent.category === "PNUnknownCategory") {
            var newState = {
                new: 'error'
                    state: newState
                function (status) {
    message: function(message) {

    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:

    channels: ['some_channel']

Try PubNub Today