Publish/Subscribe API for PubNub EON Chart SDK

Publish

The publish() function is used to send a message to all subscribers of a channel. To publish a message you must first specify a valid publishKey at initialization. A successfully published message is replicated across the PubNub Real-Time Network and sent simultaneously to all subscribed clients on a channel.

Messages in transit can be secured from potential eavesdroppers with SSL/TLS by setting ssl to true during initialization.

Publish Anytime

It's not required to be subscribed to a channel in order to publish to that channel.

Message Data

The message argument can contain any JSON serializable data, including: Objects, Arrays, Ints and Strings. data should not contain special EON Chart classes or functions as these will not serialize. String content can include any single-byte or multi-byte UTF-8 character.

Don't Use JSON.stringify

It is important to note that you should not use JSON.stringify() when sending signals/messages via PubNub. Why? Because the serialization is done for you automatically. Instead just pass the full object as the message payload. PubNub takes care of everything for you.

Message Size

The maximum number of characters per message is 32 KiB by default. The maximum message size is based on the final escaped character count, including the channel name. An ideal message size is under 1800 bytes which allows a message to be compressed and sent using single IP datagram (1.5 KiB) providing optimal network performance.

If the message you publish exceeds the configured size, you will receive the following message:

Message Too Large Error
["PUBLISHED",[0,"Message Too Large","13524237335750949"]]

For further details, check Calculating Message Payload Size Before Publish.

Message Publish Rate

Messages can be published as fast as bandwidth conditions will allow. There is a soft limit based on max throughput since messages will be discarded if the subscriber can't keep pace with the publisher.

For example, if 200 messages are published simultaneously before a subscriber has had a chance to receive any messages, the subscriber may not receive the first 100 messages because the message queue has a limit of only 100 messages stored in memory.

Publishing to Multiple Channels

It is not possible to publish a message to multiple channels simultaneously. The message must be published to one channel at a time.

Publishing Messages Reliably

There are some best practices to ensure messages are delivered when publishing to a channel:

  • Publish to any given channel in a serial manner (not concurrently).
  • Check that the return code is success (for example, [1,"Sent","136074940..."])
  • Publish the next message only after receiving a success return code.
  • If a failure code is returned ([0,"blah","<timetoken>"]), retry the publish.
  • Avoid exceeding the in-memory queue's capacity of 100 messages. An overflow situation (aka missed messages) can occur if slow subscribers fail to keep up with the publish pace in a given period of time.
  • Throttle publish bursts in accordance with your app's latency needs, for example, Publish no faster than 5 msgs per second to any one channel.

Method(s)

To Publish a message you can use the following method(s) in the EON Chart SDK:

publish( {Object message, String channel, Boolean storeInHistory, Boolean sendByPost, Object meta, Number ttl }, Function callback )
ParameterTypeRequiredDefaultDescription
Operation ArgumentsHashYesA hash of arguments.
messageObjectYesThe message may be any valid JSON type including objects, arrays, strings, and numbers.
channelStringYesSpecifies channel name to publish messages to.
storeInHistoryBooleanOptionaltrueIf true the messages are stored in history.
If storeInHistory is not specified, then the history configuration on the key is used.
sendByPostBooleanOptionalfalseIf true the messages are sent via POST.
metaObjectOptionalPublish extra meta with the request.
ttlNumberOptionalSet a per message time to live in Message Persistence.
  1. If storeInHistory = true, and ttl = 0, the message is stored with no expiry time.
  2. If storeInHistory = true and ttl = X (X is an Integer value), the message is stored with an expiry time of X hours.
  3. If storeInHistory = false, the ttl parameter is ignored.
  4. If ttl is not specified, then expiration of the message defaults back to the expiry value for the key.
callbackFunctionOptionalExecutes on a successful/unsuccessful publish.

Basic Usage

Publish a message to a channel

pubnub.publish(
{
message: {
such: 'object'
},
channel: 'my_channel',
sendByPost: false, // true to send via post
storeInHistory: false, //override default storage options
meta: {
"cool": "meta"
} // publish extra meta with the request
},
function (status, response) {
if (status.error) {
// handle error
show all 21 lines
Subscribe to the channel

Before running the above publish example, either using the Debug Console or in a separate script running in a separate terminal window, subscribe to the same channel that is being published to.

Response

type PublishResponse = {
timetoken: number
}

Other Examples

Custom

Notice how the code below publishes a key value pair called x with every message.

pubnub.publish({
channels: 'c3-spline',
message: {
eon: {
'x': new Date().getTime(),
'Austin': Math.floor(Math.random() * 99)
}
}
});

Multiple Points Per Payload

It is possible to publish multiple plot points per payload. Rather than using the object name eon use the name eons and supply an Array. Because you use the eons property name, the library will know to loop through the array and plot each point. Note that if publishing multiple points per payload, you must use xType: "custom" and supply an xId.

eons: [
{
x: new Date().getTime(),
value: 1
},{
x: new Date().getTime(),
value: 2
}
]

Here's an example of data collected at 100ms increments, but only publishes every 1,000ms. Every payload includes 10 points with 100ms resolution. See a full example here.

setInterval(function(){
let data = [];
let date = new Date().getTime();

for(let i = 0; i < 10; i++) {
data.push({
'pub_time': date + (100 * i),
'Austin': Math.floor(Math.random() * 99)
});
}

pubnub.publish({
channels: [channel],
message: {
eons: data
show all 19 lines

Disable

You can disable eon-chart modifications by setting xType to false. By default C3 will use an incremental x axis (1,2,3,4...).

Distributed Systems

You can publish from multiple sources into one chart. For example, you can graph the individual memory usage from 3 servers by supplying the same channel to your PubNub publish requests. Check out our distributed chart example.

Last updated on