PubNub Stream Controller Tutorial

Add channels to groups and control multiple PubNub Data Streams with Stream Controller
PubNub Stream Controller Tutorial

PubNub Stream Controller Tutorial

PubNub's Stream Controller feature allows you to receive messages on multiple channels from a single network connection. This vastly extends one's ability to connect to, and manage, large numbers of streams while keeping bandwidth costs to a minimum.

Stream Controller comes in two flavors:

  • Multiplexing - enables you to subscribe to 50 channels over a single TCP socket
  • Channel Groups - allows you to bundle thousands of channels into a "group" that can be identified by name

Stream Controller also comes with a feature that lets you to subscribe multiple channel using wildcard notation.

  • Chat rooms: allowing users to chat on multiple rooms simultaneously
  • News Feed: connecting to multiple news feeds
  • Chat rooms: grouping the chat rooms (e.g. "Sports" room includes "Baseball", "Football", etc. rooms)
  • Stock Trade: categorizing stock tickers by market (e.g. "AAPL", "AMZN" channels under, "tech-stocks")

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

Enable Stream Controller Add-on

 

You can enable additional configuration, Wildcard Subscribe at the configuration modal dialog. You can always come back to your admin dashboard to modify the settings later.

Enable Wildcard Subscribe

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.

pubnub.subscribe({
    channels: ["news", "cats", "gadgets"]
});
pubnub.subscribe({
    channels: ["movies", "ama"]
});
 
// more of your code goes here
// then subscribe to more channels later
 
pubnub.subscribe({
    channels: ["funny-pic", "worldnews", "programming"]
});

Although the number of multiplexed channels can be as high as 50, as a best practice it is always a good idea to keep the number small.

If you will be more commonly supporting greater than 10 channel subscriptions per client connection, you should bly consider using channel groups.

Channel Groups are, simply, groups of channels managed server-side that can all be subscribed to with a single call. The channel limit per group is 2,000 and each client connection can subscribe to 10 total channel groups, for a total of 20,000 channels.

Channel Groups are useful for "friends & followers" design patterns à la Facebook and Twitter. 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.

You can add channels into a channel group using channelGroups.addChannels() method:

pubnub.channelGroups.addChannels(
    {
        channels: ["aapl", "amzn", "twtr"],
        channelGroup: "tech-stocks"
    }, 
    function(status) {
        if (status.error) {
            console.log("operation failed w/ status: ", status);
        } else {
            console.log("operation done!")
        }
    }
);

You can remove channels from a channel group using channelGroups.removeChannels() method:

pubnub.channelGroups.removeChannels(
    {
        channels: ["aapl"],
        channelGroup: "tech-stocks"
    },
    function (status) {
        if (status.error) {
            console.log("operation failed w/ error:", status);
        } else {
            console.log("operation done!")
        }
    }
);

You can get a list of all the channels defined within a channel group with channelGroups.listChannels() method:

pubnub.channelGroups.listChannels(
    {
        channelGroup: "tech-stocks"
    }, 
    function (status, response) {
        if (status.error) {
            console.log("operation failed w/ error:", status);
            return;
        }
         
        console.log("listing push channel for device")
        response.channels.forEach( function (channel) {
            console.log(channel)
        })
    }
);

You can remove a channel group using channelGroups.deleteGroup() method:

pubnub.channelGroups.deleteGroup(
    {
        channelGroup: "tech-stocks"
    },
    function (status) {
        if (status.error) {
            console.log("operation failed w/ error:", status);
        } else {
            console.log("operation done!")
        }
    }
);

You subscribe to a channel group just like you would subscribe to a regular channel:

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

pubnub.subscribe({
    channelGroups: ["tech-stocks"]
});

The channel group cannot be empty. Without channels, a channel group cannot exist.

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 or removed to the channel group on the server-side, your client is immediately subscribed or unsubscribed, respectively, to that channel as well.

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

You can also unsubscribe from a channel group:

pubnub.unsubscribe({
    channelGroups: ["tech-stocks"]
});

To be able to use this additional feature, you need to enable Wildcard Subscribe at the configuration dialog.

Wildcard subscribes allow the client to subscribe to multiple channels using wildcard. For instance, if you subscribe to a.* you will get all messages for a.b, a.c, a.x. The wildcarded * portion refers to any portion of the channel string name after the dot (.).

  • a.*
  • a.b.*
  • sports.*

For example, when you subscribe the wildcarded sports.* channel, you are actually subscribing all existing channels that starts with sports., such as sports.baseball, sports.basketball, sports.football and so on.

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

pubnub.subscribe({
    channels: ["sports.*"]
});
  • *
  • .*
  • a*
  • a.
  • a*b
  • a.*.b

The above invalid channel names will actually succeed if you attempt to subscribe to them. However, they will not operate as literal channel names and not as wildcard channels.

You can take a look at: the bottom of the page of this Stream Controller Getting Started Guide.

Tags: 
Stream Controller