Publish/Subscribe API for PubNub AngularJS 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 AngularJS 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 (e.g.
[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 e.g. 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 AngularJS SDK:
-
publish( {Object message, String channel, Boolean storeInHistory, Boolean sendByPost, Object meta, Number ttl }, Function callback )
Parameter Type Required Default Description Operation Arguments Hash Yes A hash of arguments. message
Object Yes The message
may be any valid JSON type including objects, arrays, strings, and numbers.channel
String Yes Specifies channel
name to publish messages to.storeInHistory
Boolean Optional true
If true
the messages are stored in history.
IfstoreInHistory
is not specified, then the history configuration on the key is used.sendByPost
Boolean Optional false
When true
, the SDK uses HTTP POST to publish the messages. The message is sent in the BODY of the request, instead of the query string when HTTP GET is used. Also the messages are compressed thus reducing the size of the messages. Using HTTP POST to publish messages adheres to RESTful API best practices.meta
Object Optional Publish extra meta
with the request.ttl
Number Optional Set a per message time to live in Message Persistence. - If
storeInHistory
=true
, andttl
=0
, the message is stored with no expiry time. - If
storeInHistory
=true
andttl
=X
(X
is an Integer value), the message is stored with an expiry time ofX
hours. - If
storeInHistory
=false
, thettl
parameter is ignored. - If
ttl
is not specified, then expiration of the message defaults back to the expiry value for the key.
callback
Function Optional Executes on a successful/unsuccessful publish
. - If
Basic Usage
Publish a message to a channel:
Pubnub.publish(
{
message: {
such: 'Hello from the PubNub Javascript SDK!'
},
channel: 'my_channel'
},
function (status, response) {
if (status.error) {
// handle error
console.log(status);
} else {
console.log("message Published w/ timetoken", response.timetoken);
}
}
show all 16 linesNote
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
-
Publish a JSON serialized message
show all 16 linesvar newMessage = {
text: 'Hi There!'
}
Pubnub.publish(
{
message: newMessage,
channel: 'my_channel'
},
function(status, response) {
if (status.error) {
console.log("publishing failed w/ status: ", status);
} else {
console.log("message published w/ server response: ", response);
}
} -
Store the published message for 10 hours
Pubnub.publish(
{
message: 'hello!',
channel: 'my_channel',
storeInHistory: true,
ttl: 10
},
function(status, response) {
if (status.error) {
console.log("publishing failed w/ status: ", status);
} else {
console.log("message published w/ server response: ", response);
}
}
);
Fire
The fire endpoint allows the client to send a message to Functions Event Handlers and Illuminate. These messages will go directly to any Event Handlers registered on the channel that you fire to and will trigger their execution. The content of the fired request will be available for processing within the Event Handler. The message sent via fire()
isn't replicated, and so won't be received by any subscribers to the channel. The message is also not stored in history.
Method(s)
To Fire a message
you can use the following method(s) in the AngularJS SDK:
-
fire( {Object message, String channel, Boolean sendByPost, Object meta}, Function callback )
Parameter Type Required Default Description Operation Arguments Hash Yes A hash of arguments. message
Object Yes The message
may be any valid JSON type including objects, arrays, strings, and numbers.channel
String Yes Specifies channel
name to publish messages to.sendByPost
Boolean Optional false
If true
the messages sent via POST.meta
Object Optional Publish extra meta
with the request.callback
Function Optional Executes on a successful/unsuccessful publish
.
Basic Usage
Fire a message to a channel:
Pubnub.fire(
{
message: {
such: 'Hello from the PubNub Javascript SDK!'
},
channel: 'my_channel'
},
function (status, response) {
if (status.error) {
// handle error
console.log(status);
} else {
console.log("message fired w/ timetoken", response.timetoken);
}
}
show all 16 linesSubscribe
This function causes the client to create an open TCP socket to the PubNub Real-Time Network and begin listening for messages on a specified channel
. To subscribe to a channel
the client must send the appropriate subscribeKey
at initialization. By default a newly subscribed client will only receive messages published to the channel after the subscribe()
call completes.
Tip
You can be notified of connectivity via the listener, on establishing connection the statusEvent.category
returns PNConnectedCategory
.
By waiting for the connect event to return before attempting to publish, you can avoid a potential race condition on clients that subscribe and immediately publish messages before the subscribe
has completed.
Warning
Unsubscribing from all channels, and then subscribing to a new channel Y is not the same as subscribing to channel Y and then unsubscribing from the previously-subscribed channel(s). Unsubscribing from all channels resets the last-received timetoken
and thus, there could be some gaps in the subscription that may lead to message loss.
Method(s)
To Subscribe to a channel
you can use the following method(s) in the AngularJS SDK:
subscribe({Array channels, Array channelGroups, Boolean withPresence, Number timetoken})
Parameter | Type | Required | Default | Description |
---|---|---|---|---|
Operation Arguments | Hash | Yes | A hash of arguments. | |
channels | Array | Yes | Specifies the channels to subscribe to. It is possible to specify multiple channels as a list or as an array. | |
channelGroups | Array | Specifying either channels or channelGroups is mandatory | Specifies the channelGroups to subscribe to. | |
withPresence | Boolean | Optional | false | If true it also subscribes to presence instances. |
timetoken | Number | Optional | Specifies timetoken from which to start returning any available cached messages. Message retrieval with timetoken is not guaranteed and should only be considered a best-effort service. |
Basic Usage
Subscribe to a channel:
// Subscribe to a channel
Pubnub.addListener({
status: function(statusEvent) {
if (statusEvent.category === "PNUnknownCategory") {
var newState = {
new: 'error'
};
Pubnub.setState(
{
state: newState
},
function (status) {
console.log(statusEvent.errorData.message)
}
);
show all 25 linesReturns
The following objects will be returned in the Status Response
Object | Description |
---|---|
category | PNConnectedCategory |
operation | PNSubscribeOperation |
affectedChannels | The channels affected in the operation, of type array. |
subscribedChannels | All the current subscribed channels, of type array. |
affectedChannelGroups | The channel groups affected in the operation, of type array. |
lastTimetoken | The last timetoken used in the subscribe request, of type long. |
currentTimetoken | The current timetoken fetched in the subscribe response, which is going to be used in the next request, of type long. |
{
category: 'PNConnectedCategory',
operation: 'PNSubscribeOperation',
affectedChannels: ['my_channel_1'],
subscribedChannels: ['my_channel_1'],
affectedChannelGroups: [],
lastTimetoken: '14974492380756600',
currentTimetoken: '14974492384874375'
}
The following objects will be returned in the Subscribe Message Response
Object | Description |
---|---|
channel | The channel for which the message belongs. |
subscription | The channel group or wildcard subscription match (if exists). |
timetoken | Publish timetoken . |
message | The payload . |
actualChannel | Deprecated. Use property channel . |
subscribedChannel | Deprecated. Use property subscription . |
{
actualChannel: null,
channel: "my_channel_1",
message: "Hello World!",
publisher: "pn-58e1a647-3e8a-4c7f-bfa4-e007ea4b2073",
subscribedChannel: "my_channel_1",
subscription: null,
timetoken: "14966804541029440"
}
The following objects will be returned in the Presence Response
Object | Description |
---|---|
action | Can be join , leave , state-change or timeout . |
channel | The channel for which the message belongs. |
occupancy | No. of users connected with the channel . |
state | User State. |
subscription | The channel group or wildcard subscription match (if exists) |
timestamp | Current timetoken . |
timetoken | Publish timetoken . |
uuid | UUIDs of users who are connected with the channel . |
{
category: 'PNConnectedCategory',
operation: 'PNSubscribeOperation',
affectedChannels: ['my_channel_1'],
subscribedChannels: ['my_channel_1'],
affectedChannelGroups: [],
lastTimetoken: '14974492380756600',
currentTimetoken: '14974492384874375'
}