Give Feedback for the page
Add Publish Subscribe to any app with PubNub Data Streams

Publish/Subscribe Getting Started Guide

Add publish subscribe to any app in 5 easy steps with PubNub Data Streams

Publish/Subscribe Getting Started Guide

1

Install PubNub

To start publishing and subscribing, we first need to access our PubNub libraries. Include the code hosted on our CDN just before closing your HTML </body> tag.

Now you can instantiate a PubNub object using your own publish and subscribe keys or use our demo keys.


/* View the Full Documentation. */
/* Instantiate PubNub */
PNConfiguration pnConfiguration = new PNConfiguration();
pnConfiguration.setPublishKey("Your Publish Key Here");
pnConfiguration.setSubscribeKey("Your Subscribe Key Here");

PubNub pubnub = new PubNub(pnConfiguration);


/* View the Full Documentation. */
/* Instantiate PubNub */
PNConfiguration *configuration = [PNConfiguration configurationWithPublishKey:@"Your publish key" 
                                                                                                                                                                             subscribeKey:@"Your subscribe key"];
self.client = [PubNub clientWithConfiguration:configuration];
[self.client addListener:self];


<!-- View the Full Documentation. -->
<!-- Include the PubNub Library -->
<script src="https://cdn.pubnub.com/sdk/javascript/pubnub.[version number].js"></script>

<!-- Instantiate PubNub -->
<script type="text/javascript">

    var pubnubDemo = new PubNub({
        publishKey: 'Your Publish Key Here',
        subscribeKey: 'Your Subscribe Key Here'
    });

</script>


//  View the Full Documentation.
// Instantiate PubNub
Pubnub pubnub = new Pubnub(
   publishKey:"Your Publish Key Here", 
   subscribeKey:"Your Subscribe Key Here"
);

/***************
For all other languages,
check out the 70+ SDKs that PubNub supports
on our documentation page:
/docs
****************/

2

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 */
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 http://www.pubnub.com/docs/ios-objective-c/api-reference#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
pubnubDemo.addListener({
    message: function(message){
        console.log(message)
    }
})

pubnubDemo.subscribe({
    channels: ['demo_tutorial']
});


// Subscribe to the demo_tutorial channel
pubnub.Subscribe<string>(
   channel:"demo_tutorial", 
   DisplaySubscribeReturnMessage, 
   DisplaySubscribeConnectStatusMessage, 
   DisplayErrorMessage);
   
// NOTE: DisplaySubscribeReturnMessage, DisplaySubscribeConnectStatusMessage and DisplayErrorMessage are callback methods


/***************
For all other languages,
check out the 70+ SDKs that PubNub supports
on our documentation page:
/docs
****************/

3

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 */
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
pubnubDemo.publish({
    message: {
        "color" : "blue"
    },
    channel: 'demo_tutorial'
});


// Publish a simple message to the demo_tutorial channel

pubnub.Publish<string>(
   channel:"demo_tutorial", 
   publishMsg:"{\"color\":\"blue\"}", 
   DisplayReturnMessage, 
   DisplayErrorMessage);

// NOTE: DisplayReturnMessage and DisplayErrorMessage are callback methods
// NOTE: For direct JSON message publish, 
         add "pubnub.EnableJsonEncodingForPublish = false;" before calling Publish;


/***************
For all other languages,
check out the 70+ SDKs that PubNub supports
on our documentation page:
/docs
****************/

4

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 »

5

Congratulations!

With those few steps, you've built your first PubNub application. Now the right thing to do is Tweet Your Success!

Next, Sign Up for a free PubNub account. Then add features like Security, Presence, and Storage to make your app more robust.

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

logos

Try PubNub Today

Connect up to 100 devices for Free