Message Publish

The foundation of all our PubNub offering is the ability to send a message and it will be delivered anywhere in less than 100ms. Below we will walk step by step to understand different ways of sending a message.

Receiving messages

We hope you already know you need to add a listener to receive and handle incoming messages, signals, and events.

If you're new to PubNub, make sure to check out how to set up your account as well.

Sending Messages

The primary means for sending messages is using the Publish API. You may only send a message to one channel at a time. PubNub's network supports sending unlimited publishes without waiting for response on the same TCP socket connection.

pubnub.publish(
{
channel: "my_channel",
message: {"text": "Hello World!"}
},
function(status, response) {
console.log(status);
console.log(response);
}
);

When you publish a message to a channel, you're asking PubNub Platform to deliver that message to everyone who is subscribed to that channel.

A PubNub message may be sent as plain text, URL-encoded object, and most commonly, JSON. For more information, refer to message types.

As you can see, in the above publish method we specify the channel on which to send the message, the message content we want to send and a way to capture the server response, which in most languages is an asynchronous callback. A successful response looks like this:

[1,"Sent","14375189629170609"]

The response has three parts:

  1. success flag: 1 = success, 0 = failed
  2. response message: Sent or Failed
  3. publish timetoken: exact timestamp of the message which is a 17 digit value to the nearest 10th nanosecond (can be converted to UNIX epoch by dividing by 10000).

The publish timetoken can be used later to retrieve (or augment) that message using PubNub Storage.

HTTP Streaming and Pipelining

For more information about streaming and pipelining, refer to this gist.

Sending announcements to all users

You can send announcements to all users, or a limited set of users, in your application by using a channel to which the announcer has read/write access, and to which all other users have read-only access.

Once you have the channel set up, you can display any messages sent on the channel as announcements. Users with read access can subscribe to the channel to receive announcements, but can't send messages on the same channel.

pubnub.publish({
message: {
type: 'announcement',
text: 'Hello, this is an announcement'
},
channel: 'ch-1',
}, (status, response) => {
// handle status, response
});

Message Specifications

The message property can contain any JSON serializable data (JSON isn't required, just recommended and is typical in most use cases), including: Objects, Arrays, Integers and Strings. String content can include any single-byte or multi-byte UTF-8 character.

JSON Serialization

There is no need to serialize your JSON object when sending messages via PubNub Platform. PubNub SDKs does that for you.

Delivery

Though we provide as much information about the delivery as possible, PubNub is not a guaranteed message delivery service, as there is no way to guarantee that the network connection between the subscribers and PubNub has not been interrupted.

For example, while the Sent status code returned to the message publisher does not guarantee that the message is delivered, it does mean that the PubNub Network has received the message and has already sent it along to all currently connected subscribers.

We are constantly adding features which improve deliverability but the quality of service of the last mile of connectivity is not within PubNub's control.

Subscribers with troubled connections or that were offline by intention can still retrieve missed messages. For more information about status codes, and retrieving missed and historical messages, refer to Connection Management and Storage.

Order

As long as the publisher sends messages at a slower rate than the consumer can receive them, you can assume with high confidence that messages will be kept in order.

However, PubNub doesn't guarantee that messages are stored or sent in the exact same order in which they're published. If your application requires messages to be processed in the same order they were published, we recommend adding a sequence field to the message payload and use it to order messages by.

Message Size Limit

The maximum number of characters per message is 32 KiB. The maximum message size is based on the final escaped character count, including the channel name.

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

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

If you expect your messages will be pushing the size limit, check out the PubNub KB article, Calculating Message Payload Size Before Publish.

Receiving Messages

To receive a message, your client should implement a message listener and subscribe to a channel in which the message is being published.

Sending Signals

Signals are ideal for high-volume, low-cost use cases. They're intended for sending small bits of data where the last sent data is the only important piece of information. For example, chat typing indicators, live GPS location updates, and sensor updates from IoT devices.

Messages vs Signals

Signals are similar to regular messages, with the following exceptions:

  • The message size is limited to 64 bytes or less
  • Signals cost less
  • A signal's data can't be persisted in storage, and hence you can't access previous signals
  • There are no SLAs, even though signals generally provide the same reliability and latency as published messages
  • Signals can't invoke Push Notifications

Sending a signal is similar to publishing a message:

let gps = ["35.9296","-78.9482"];

pubnub.signal(
{
channel: "locations.route1",
message: gps
},
function(status, response) {
console.log(status, response);
}
);

The Signal response may not be as important to your application and could be omitted, but is dependent on your use case.

Receiving Signals

To receive a signal, your client should implement a signal listener and subscribe to a channel in which the signal is being sent.

Publishing with Filter

Message Filters allow a client to send Messages to only those clients that satisfy the conditions of the filter. To use Message Filters, it's important to include filtering conditions when publishing a new message. The meta parameter isn't a part of the message data and allows subscribing clients to filter based on the included information.

Filtering origin

The filtering takes place server-side.

To include metadata that can be used for filters, prepare the data and pass it to the publishing function.

pubnub.publish(
{
channel: "chats.room1",
message: "Hello to everyone (except me)",
meta: {
uuid: pubnub.getUUID()
}
},
function(status, response) {
console.log(status, response);
}
);

In the above example, the metadata will allow the client to filter messages based on the UUID of the sender.

Filter Language Definition

The filtering language is extensive and supports many advanced use cases. Here are some common filter examples:

ExpressionMeaning
string == 'match'Exact match
string LIKE 'match*'Asterisk wildcarding, case insensitive
string LIKE 'match\*'Literal match with string containing asterisk character
('Anne','anna','Ann') LIKE 'ann*'Any of the three set members would be a sufficient match
('a','b','c') CONTAINS stringCompare against a list of values
otherstring CONTAINS stringCheck for a substring match
(3,5,9) contains numValueCompare number to a list of values
!((3,5,9) contains numValue)Negation
string contains numValuestr(numValue) in string
numValue > (numA + numB - numC)Compare number to an arithmetic expression
(numA ^ numB) != (numValue * 10)Compare two expressions
(~numA / numB)numValue

Filter Expression Language Specification

compound_expression is root.

ExpressionComment
<compound_expression><expression> | <expression> <binary_logical_op> <expression>
<binary_logical_op>&& | ||
<expression>(<expression>) | <operand> <comparison_operator> <operand> | <unary_logical_op> <operand>
<numeric_comparison_operator>{==, !=, <, >, <=, >=}
<string_comparison_operator>{contains, like}
<unary_logical_op>!
<operand>(<operand>) | <unary_op> <operand> | <literals> <binary_op> <literals>
<unary_op>~
<binary_op>|, |, ^, +, -, /, *