Real time data push using PUB NUB in JavaScript


We are going to see how to use PUB NUB when you want to push data in real time.

Pub Nub help us to attain our objective in easy and effective way.

We need the API’s keys and you will get it by signing in the PUB NUB account.

There will be two keys : publish_key and subscribe_key .

The publish_key allows us to send our data to a channel while to receive the data from a channel subscribe_key is required.

As we will be using both the publish and subscribe API’s we need both the key.

After we get the keys it’s time to add them to our application.

We can add the key either through JavaScript or directly in HTML page.

Addition through JavaScript.


<script>

var pubnub = PUBNUB.init({
publish_key : 'demo',
subscribe_key : 'demo'
})

</script>

Adding directly to your HTML page.


<div pub-key="publish-key"
sub-key="suscribe-key"
origin="pubsub.pubnub.com" id="pubnub">
</div>

Once both keys are added we call the it’s the time to add JavaScript SDK to our application.


<script src=http://cdn.pubnub.com/pubnub.min.js ></script>

Adding the above code adds the JavaScript API in our application.

Now we are ready to send and receive the data through PUB NUB in real time.

PUB NUB provides us simple API’s.

For sending the message or data we are given the publish API while subscribe API is there for receiving the message.

The publish API sends data through a unique channel and once the data is sent it is received by the subscribe API that is subscribed to the channel through which publish API have sent the data.

Add the publish API to send a message through a channel.


pubnub.publish({
channel: 'Demo',
message: 'Hello'
});

Once the message is send to a channel we need a subscribe API to receive the message.

The below code will do the work.

pubnub.subscribe({
channel: 'Demo',
message: function(data){alert(data)}
});

And we are done. Now when ever a message is published through the channel Demo it will be available at subscriber end in real time.

 

This entry was posted in Scala. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s