PubNub

Getting started with PubNub

Remarks#

This is an simple, yet thorough, example of initializing PubNub, subscribing to a channel and publishing to that channel.

  • Once you init PUBNUB, you can subscribe to a channel.
  • The connect callback indicates that subscription to the channel was successful, so we call our pub function which performs a publish to the channel we just subscribed to.
  • This published message will be sent to the PubNub network which will send the message to all active subscribers. In this case, it is just us so we will receive that message in our message callback where we are displaying the various attributes of the received message to our browser’s Console.

In a real world use case, you would update your web page UI to display the received message.

See also: latest/official PubNub JavaScript SDK Docs

Versions#

VersionRelease Date
3.15.x2016-04-01

Publish on Subscribe Success (connect)

This example show how to subscribe, and once that is successful, publishing a message to that channel. It also demonstrates the full set of parameters that can be included in the subscribe’s message callback function.

pubnub = PUBNUB({                          
    publish_key   : 'your_pub_key',
    subscribe_key : 'your_sub_key'
});

pubnub.subscribe({                                     
    channel : "channel-1",
    message : function (message, envelope, channelOrGroup, time, channel) {
        console.log(
        "Message Received." + "\n" +
        "Channel or Group: " + JSON.stringify(channelOrGroup) + "\n" +
        "Channel: " + JSON.stringify(channel) + "\n" +
        "Message: " + JSON.stringify(message) + "\n" +
        "Time: " + time + "\n" +
        "Raw Envelope: " + JSON.stringify(envelope)
    )},
    connect:    pub,
    disconnect: function(m) {console.log("DISCONNECT: " + m)},
    reconnect:  function(m) {console.log("RECONNECT: " + m)},
    error:      function(m) {console.log("ERROR: " + m)}
});

function pub() {
   pubnub.publish({                                    
        channel : "channel-1",
        message : {"msg": "I'm Puuumped!"},
        callback: function(m) {console.log("Publish SUCCESS: " + m)},
        error: function(m) {console.log("Publish ERROR: " + m)}
   })
};

This modified text is an extract of the original Stack Overflow Documentation created by the contributors and released under CC BY-SA 3.0 This website is not affiliated with Stack Overflow