Stream Controller Quickstart

Stream Controller Quickstart

1

Install PubNub

To start publishing and subscribing, we first need to access PubNub libraries. Include the libraries from CDN or from popular package managers.

View Full JavaScript SDK Documentation
<!-- Include the PubNub Library -->
<script src="https://cdn.pubnub.com/sdk/javascript/pubnub.4.27.3.js"></script>
View Full Android SDK Documentation
// Using Maven
<dependency>
  <groupId>com.pubnub</groupId>
  <artifactId>pubnub-gson</artifactId>
  <version>4.29.2</version>
</dependency>
View Full iOS SDK Documentation
# Create framework using cocoapods
git clone git@github.com:pubnub/objective-c.git

pod install
View Full .NET SDK Documentation
// Using Nuget
https://www.nuget.org/packages/Pubnub/4.5.0.0
/***************
For the 70+ SDKs that PubNub supports go to:
http://www.pubnub.com/docs
****************/

2

Instantiate PubNub

Now you can instantiate a PubNub object using your own publish and subscribe keys.

<!-- Instantiate PubNub -->
<script type="text/javascript">
    var pubnub = new PubNub({
        publishKey: "myPublishKey",
        subscribeKey: "mySubscribeKey",
        ssl: true
    });
</script>
/* Instantiate PubNub */
PNConfiguration pnConfiguration = new PNConfiguration();
pnConfiguration.setPublishKey("myPublishKey");
pnConfiguration.setSubscribeKey("mySubscribeKey");

PubNub pubnub = new PubNub(pnConfiguration);
/* Instantiate PubNub */
PNConfiguration *configuration = [PNConfiguration configurationWithPublishKey:@"myPublishKey" subscribeKey:@"mySubscribeKey"];
self.client = [PubNub clientWithConfiguration:configuration];
[self.client addListener:self];
/* Instantiate PubNub */
PNConfiguration pnConfiguration = new PNConfiguration();
pnConfiguration.PublishKey = "myPublishKey";
pnConfiguration.SubscribeKey = "mySubscribeKey";

Pubnub pubnub = new Pubnub(pnConfiguration);
/***************
For the 70+ SDKs that PubNub supports go to:
http://www.pubnub.com/docs
****************/

3

Enable Channel Groups

Enable Channel Groups on your keys in the Admin Console to use this feature.

4

Add Channels to a Channel Group

Adding channels to a Channel Group is as simple as the single methods shown in the code snippets to the right. Specify both the channel you want to add and the Channel Group you want to add it to.

Channel groups are created when a channel is added to it, no need to worry about creating one before hand.

pubnub.channelGroups.addChannels(
    {
        channels: ["BIOF"],
        channelGroup: "energy"
    },
    function(status) {
        if (status.error) {
            console.log("operation failed w/ status: ", status);
        } else {
            console.log("operation done!");
        }
    }
);
pubnub.addChannelsToChannelGroup()
    .channelGroup("energy")
    .channels(Arrays.asList("BIOF"))
    .async(new PNCallback<PNChannelGroupsAddChannelResult>() {
        @Override
        public void onResponse(PNChannelGroupsAddChannelResult result, PNStatus status) {

        }
    });
[self.client addChannels: @[@"BIOF"] toGroup:@"energy"
          withCompletion:^(PNAcknowledgmentStatus *status) {

    if (!status.isError) {

        // Handle successful channels list modification for group.
    }
    else {

        /**
         Handle channels list modification for group error. Check 'category' property to find out possible reason because of which request did fail.
         Review 'errorData' property (which has PNErrorData data type) of status object to get additional information about issue.

         Request can be resent using: [status retry];
         */
    }
}];
pubnub.AddChannelsToChannelGroup()
    .ChannelGroup("energy")
    .Channels(new string[] {
        "BIOF"
    })
    .Async(new PNChannelGroupsAddChannelResultExt((result, status) => {
    }));
/***************
For the 70+ SDKs that PubNub supports go to:
http://www.pubnub.com/docs
****************/

5

Subscribe to a Channel Group

As simply as we have added a channel to a group, we can then subscribe to that Channel Group using the basic subscribe call.

pubnub.addListener({
    message: function(message) {
        displayNewPrice(message);
    }
})

pubnub.subscribe({
    channelGroups: ["energy"]
});
try {
    pubnub.addListener(new SubscribeCallback() {
        @Override
        public void message(PubNub pubnub, PNMessageResult message) {
            JsonNode msg = message.getMessage();
            System.out.println(msg);
        }
     });

     pubnub.subscribe()
        .channelGroups(Arrays.asList("energy"))
        .execute();
} catch (PubnubException e) {
    e.printStackTrace();
}
[self.client subscribeToChannelGroups:@[@"energy"] withPresence:NO];

- (void)client:(PubNub *)client didReceiveStatus:(PNStatus *)status {

    if (status.operation == PNSubscribeOperation) {

        // Check whether received information about successful subscription or restore.
        if (status.category == PNConnectedCategory || status.category == PNReconnectedCategory) {

            // Status object for those categories can be casted to `PNSubscribeStatus` for use below.
            PNSubscribeStatus *subscribeStatus = (PNSubscribeStatus *)status;
            if (subscribeStatus.category == PNConnectedCategory) {

                // This is expected for a subscribe, this means there is no error or issue whatsoever.
            }
            else {

                /**
                 This usually occurs if subscribe temporarily fails but reconnects. This means there was an error but there is no longer any issue.
                 */
            }
        }
        else if (status.category == PNUnexpectedDisconnectCategory) {

            /**
             This is usually an issue with the internet connection, this is an error, handle appropriately retry will be called automatically.
             */
        }
        // Looks like some kind of issues happened while client tried to subscribe or disconnected from network.
        else {

            PNErrorStatus *errorStatus = (PNErrorStatus *)status;
            if (errorStatus.category == PNAccessDeniedCategory) {

                /**
                 This means that PAM does allow this client to subscribe to this channel and channel group configuration. This is another explicit error.
                 */
            }
            else {

                /**
                 More errors can be directly specified by creating explicit cases for other error categories of `PNStatusCategory` such as: `PNDecryptionErrorCategory`, `PNMalformedFilterExpressionCategory`, `PNMalformedResponseCategory`, `PNTimeoutCategory` or `PNNetworkIssuesCategory`
                 */
            }
        }
    }
}
try {
    pubnub.AddListener(new SubscribeCallbackExt(
        (pubnubObj, messageResult) => {
            if (messageResult != null) {
                string jsonString = messageResult.Message.ToString();
                Console.WriteLine(jsonString);
            }
        },
        (pubnubObj, presencResult) => {
        },
        (pubnubObj, statusResult) => {
            if (statusResult.Error && statusResult.Category == PNStatusCategory.PNUnknownCategory) {
                Console.WriteLine(statusResult.ErrorData.Information);
            }
        }
    ));

    pubnub.Subscribe<string>()
        .ChannelGroups(new string[] {
            "energy"
        })
        .Execute();
}
catch (Exception e) {
    Debug.WriteLine(e.ToString());
}
/***************
For the 70+ SDKs that PubNub supports go to:
http://www.pubnub.com/docs
****************/

Try PubNub Today

Try Our APIs
  • 1M Transactions
  • 1GB Data Persistence
  • All major Features