Add Publish Subscribe to any app with PubNub Data Streams

Publish/Subscribe Quickstart

Add publish subscribe to any app in 6 easy steps with PubNub.

Publish/Subscribe 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

Subscribe

Now that you have PubNub installed and instantiated, subscribe to your own custom data channel and log all sent messages over that channel on the console.​ To make the channel private, use the PubNub Access Manager or use our additional security measures.

// Subscribe to the demo_tutorial channel
pubnub.addListener({
    message: function(message) {
        console.log(message)
    }
})

pubnub.subscribe({
    channels: ['demo_tutorial']
});
/* Subscribe to the demo_tutorial channel */
try {
    pubnub.addListener(new SubscribeCallback() {
        @Override
        public void status(PubNub pubnub, PNStatus status)  {
            if (status.getCategory() == PNStatusCategory.PNUnknownCategory) {
                System.out.println(status.getErrorData());
            }
        }

        @Override
        public void message(PubNub pubnub, PNMessageResult message) {
            JsonNode msg = message.getMessage();
            System.out.println(msg);
        }
    });

    pubnub.subscribe()
        .channels(Arrays.asList("demo_tutorial"))
        .execute();
} catch (PubnubException e) {
    e.printStackTrace();
}
/* Subscribe to the demo_tutorial channel */
[self.client subscribeToChannels: @[@"demo_tutorial"] 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`
                 */
            }
        }
    }
    else if (status.operation == PNUnsubscribeOperation) {

        if (status.category == PNDisconnectedCategory) {

            /**
             This is the expected category for an unsubscribe. This means there was no error in unsubscribing from everything.
             */
        }
    }
    else if (status.operation == PNHeartbeatOperation) {

        /**
         Heartbeat operations can in fact have errors, so it is important to check first for an error.
         For more information on how to configure heartbeat notifications through the status PNObjectEventListener callback, consult /docs/ios-objective-c/api-reference-configuration#configuration_basic_usage
         */

        if (!status.isError) {
            /* Heartbeat operation was successful. */
    }
        else {
            /* There was an error with the heartbeat operation, handle here. */
        }
    }
}
/* Subscribe to the demo_tutorial channel */
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>()
        .Channels(new string[] {
            "demo_tutorial"
        })
        .Execute();
}
catch (Exception e) {
    Debug.WriteLine(e.ToString());
}
/***************
For the 70+ SDKs that PubNub supports go to:
http://www.pubnub.com/docs
****************/

4

Publish

After you have subscribed to your own channel, you can then publish your own messages to it.

// Publish a simple message to the demo_tutorial channel
pubnub.publish({
    message: {
        "color" : "blue"
    },
    channel: 'demo_tutorial'
});
/* Publish a simple message to the demo_tutorial channel */
JSONObject data = new JSONObject();

try {
    data.put("color", "blue");
} catch (JSONException e) {
    e.printStackTrace();
}

pubnub.publish()
    .message(data)
    .channel("demo_tutorial")
    .async(new PNCallback<PNPublishResult>() {
        @Override
        public void onResponse(PNPublishResult result, PNStatus status)
        {

        }
    });
/* Publish a simple message to the demo_tutorial channel */

[self.client publish: @{@"color": @"blue"} toChannel: @"demo_tutorial"
      withCompletion:^(PNPublishStatus *status) {

    if (!status.isError) {

        // Message successfully published to specified channel.
    }
    else {

        /**
         Handle message publish 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];
         */
    }
}];
/* Publish a simple message to the demo_tutorial channel */
Dictionary<string, string> data = new Dictionary<string, string>();

try {
    data.Add("color", "blue");
}
catch (Exception e) {
    Console.WriteLine(e.ToString());
}

pubnub.Publish()
    .Channel("demo_tutorial")
    .Message(data)
    .Async(new PNPublishResultExt((publishResult, publishStatus) => {
        if (publishStatus.Error) {
            Console.WriteLine("Error occured");
        }
    }));
/***************
For the 70+ SDKs that PubNub supports go to:
http://www.pubnub.com/docs
****************/

5

Send it to Another Device

Press "Send" to see your message in the console. "Stream" will automatically send greetings to your channel every second.

Scan the QR code on your mobile device to see the messages appear there, all in realtime!

{"text":"Hey!"}
            
Send
Stream




            
Scan with mobile device
Or view the stream in a
new browser window »

6

Next Steps

Congratulations! With those few steps, you've successfully used Publish Subscribe. Checkout Publish Subscribe Tutorial to see what else can you do with it.

Sign Up for a free PubNub account if you haven't already.

Get coding right away using our 70+ SDKs in your favorite language, or build on top of one of our demo applications.

Try PubNub Today

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