Message Publish
The foundation of all our PubNub offerings is the ability to send a message that will be delivered anywhere in less than 30 ms. Below, we walk you through different ways to send a message.
A PubNub Message can contain any kind of serializable data, like objects, numbers and UTF-8 encoded strings. Its format may be plain text, a URL-encoded object, or most commonly, JavaScript Object Notation (JSON). The max size of a message is 32 Kibibytes (KiB). You can check the size of your message payload using our message size calculator.
Receiving messages
Add a listener to receive and handle incoming messages, signals, and events. If you're new to PubNub, review how to set up your account.
Send messages
The primary means for sending messages is using the Publish API. You may only send a message to one channel at a time. If you want to publish to multiple channels, you must create a channel group.
PubNub's network reliably supports unlimited publishes without waiting for response on the same TCP socket connection.
- JavaScript
- Swift
- Objective-C
- Java
- C#
- Python
pubnub.publish(
{
channel: "my_channel",
message: {"text": "Hello World!"}
},
function(status, response) {
console.log(status);
console.log(response);
}
);
pubnub.publish(
channel: "my_channel",
message: ["text": "Hello World!"]
){ result in
switch result {
case let .success(response):
print("succeeded: \(response)")
case let .failure(error):
print("failed: \(error.localizedDescription)")
}
}
[self publish: @{@"text" : @"Hello World!"} toChannel:@"my_channel"
completion:^(PNPublishStatus *status) {
NSLog(@"%@status '%@'", status);
}];
JsonObject data = new JsonObject();
data.addProperty("text", "Hello World!");
Channel channel = pubnub.channel("my_channel");
channel.publish(data)
.async(result -> { /* check result */ });
Dictionary<string, string> data = new Dictionary<string, string>();
data.Add("text", "Hello World!");
pubnub.Publish()
.Channel("my_channel")
.Message(data)
.Execute(new PNPublishResultExt(
(result, status) => {
if (status.is_error()) {
Console.WriteLine("status code: " + status.ErrorData.Information);
}
else {
Console.WriteLine("timetoken: " + result.Timetoken.ToString());
}
}
show all 16 linesdef publish_callback(result, status):
if status.is_error():
print status.status_code
elif
print result.timetoken
pubnub.publish()\
.channel("my_channel") \
.message({"text": "Hello World!"})\
.pn_async(publish_callback)
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:
- success flag: 1 = success, 0 = failed
- response message: Sent or Failed
- 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 Message Persistence.
HTTP streaming and pipelining
For details on streaming and pipelining, see this gist.
Send 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.
- JavaScript
- Swift
- Java
- Unity
pubnub.publish({
message: {
type: 'announcement',
text: 'Hello, this is an announcement'
},
channel: 'ch-1',
}, (status, response) => {
// handle status, response
});
pubnub.publish(
channel: "ch-1",
message: ["type": "announcement", "text": "Announcement message to all users"]
) { result in
switch result {
case let .success(response):
print("Successful Publish Response: \(response)")
case let .failure(error):
print("Failed Publish Response: \(error.localizedDescription)")
}
}
// Java SDK uses channel-based publish
JsonObject messagePayload = new JsonObject();
messagePayload.addProperty("type", "announcement");
messagePayload.addProperty("text", "Hello, this is an announcement");
Channel channel = pubnub.channel("ch-1");
channel.publish(messagePayload)
.async(result -> { /* check result */ });
Dictionary<string, string> payload = new Dictionary<string, string>();
payload.Add("type", "announcement");
payload.Add("text", "Hello, this is an announcement");
pubnub.Publish()
.Channel("ch-1")
.Message(payload)
.Async((result, status) => {
if (!status.Error) {
Debug.Log(result.Timetoken);
} else {
Debug.Log(status.Error);
Debug.Log(status.ErrorData.Info);
}
});
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
You don’t need to serialize a JSON object when sending messages. PubNub SDKs handle serialization.
Delivery
- PubNub provides status and timing details for each publish.
- The Sent status confirms that the PubNub Network received the message and forwarded it to connected subscribers.
- Network conditions on the last mile can affect delivery outside PubNub’s control.
Subscribers with interrupted or offline connections can still retrieve missed messages. For status codes and retrieving missed and historical messages, see Connection Management and Message Persistence.
Order
As long as the publisher sends messages slower than the consumer can receive them, messages are typically kept in order.
If your app requires strict ordering, add a sequence field to the message payload and order by it.
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 the size of your message in our payload size calculator.
For more information on calculating payload size within your application, refer to our knowledge base.
Receive messages
To receive a message, your client should implement a message
listener and subscribe to a channel in which the message is being published.
Send 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:
Feature | Signals | Messages |
---|---|---|
Payload size | Limited to 64 bytes (64B) | Up to 32 kilobytes (32KB) |
Cost efficiency | Cost less than standard messages | Generally more expensive than signals |
Persistence | Cannot be saved in Message Persistence (past signals cannot be accessed) | Can be saved and accessed through Message Persistence |
Push Notifications | Cannot trigger Mobile Push Notifications | Can trigger Mobile Push Notifications |
Use case suitability | Best for non-critical data streams, like geolocation updates | Suitable for critical and non-critical use cases |
Metadata support | Do not support metadata | Support metadata |
Channel separation
Signals and messages should be sent on separate channels to improve connection recovery behaviour.
Sending a signal is similar to publishing a message:
- JavaScript
- Swift
- Objective-C
- Java
- C#
- Python
let gps = ["35.9296","-78.9482"];
pubnub.signal(
{
channel: "locations.route1",
message: gps
},
function(status, response) {
console.log(status, response);
}
);
let gps = ["35.9296","-78.9482"]
pubnub.signal(
channel: "locations.route1",
message: gps
) { result in
switch result {
case let .success(response):
print("succeeded: \(response)")
case let .failure(error):
print("failed: \(error.localizedDescription)")
}
}
NSArray *gps = [NSArray arrayWithObjects:@"35.9296,@"-78.9482",nil];
[self signal: gps toChannel: @"locations.route1"
completion:^(PNPublishStatus *status) {
NSLog(@"%@status '%@'", status);
}];
// Java SDK uses channel-based publish
String[] gps = new String[]{"35.9296","-78.9482"};
Channel channel = pubnub.channel("locations.route1");
channel.signal(gps)
.async(result -> { /* check result */ });
string[] arrayMessage = new string[] {"35.9296","-78.9482"};
pubnub.Signal()
.Message(data)
.Channel("locations.route1")
.Execute(new PNPublishResultExt(
(result, status) => {
if (status.is_error()) {
Console.WriteLine("status code: " + status.ErrorData.Information);
}
else {
Console.WriteLine("timetoken: " + result.Timetoken);
}
}
));
def signal_callback(result, status):
if status.is_error():
print status.status_code
elif
print result.timetoken
pubnub.signal()\
.channel("locations.route1") \
.message({"msg": "Hello, my friend!"})\
.pn_async(signal_callback)
The Signal response may not be as important to your application and could be omitted, but is dependent on your use case.
Receive signals
To receive a signal, your client should implement a signal
listener and subscribe to a channel in which the signal is being sent.
Publish with metadata fields
The meta
parameter allows you to attach additional data to messages that remains separate from the message payload. Metadata fields serve two important purposes in PubNub applications: enabling subscribe filtering and maintaining data accessibility when using message encryption.
Subscribe filtering
Metadata fields can be filtered using subscribe filters, enabling server-side message routing based on user roles, priorities, geographic location, or other criteria.
Key benefits of metadata fields include:
- Subscribe filtering support - Metadata fields can be filtered using subscribe filters, enabling sophisticated message routing based on user roles, priorities, geographic location, or other criteria
- Encryption compatibility - When using AES-256 or other message encryption, metadata fields remain unencrypted and accessible to PubNub services like Functions, Illuminate, and Subscribe Filtering, while the message payload stays encrypted
To include metadata with your published messages, prepare the metadata object and pass it via the meta
parameter.
User ID / UUID
User ID is also referred to as UUID
/uuid
in some APIs and server responses but holds the value of the userId
parameter you set during initialization.
- JavaScript
- Swift
- Objective-C
- Java
- C#
- Python
// Publishing with comprehensive metadata
pubnub.publish(
{
channel: "notifications",
message: {
title: "System Maintenance",
body: "Scheduled maintenance window starting soon",
timestamp: new Date().toISOString()
},
meta: {
priority: "high",
department: "engineering",
region: "San Francisco",
publisher: pubnub.getUserId(),
requiresAck: true
show all 21 lines// Publishing with comprehensive metadata
pubnub.publish(
channel: "notifications",
message: [
"title": "System Maintenance",
"body": "Scheduled maintenance window starting soon",
"timestamp": ISO8601DateFormatter().string(from: Date())
],
meta: [
"priority": "high",
"department": "engineering",
"region": "San Francisco",
"publisher": pubnub.configuration.userId,
"requiresAck": true
]
show all 24 lines// Publishing with comprehensive metadata
NSDictionary *message = @{
@"title": @"System Maintenance",
@"body": @"Scheduled maintenance window starting soon",
@"timestamp": [[NSDateFormatter new] stringFromDate:[NSDate date]]
};
NSDictionary *meta = @{
@"priority": @"high",
@"department": @"engineering",
@"region": @"San Francisco",
@"publisher": self.pubnub.currentConfiguration.uuid,
@"requiresAck": @YES
};
show all 20 lines// Publishing with comprehensive metadata
Map<String, Object> message = new HashMap<>();
message.put("title", "System Maintenance");
message.put("body", "Scheduled maintenance window starting soon");
message.put("timestamp", Instant.now().toString());
Map<String, Object> meta = new HashMap<>();
meta.put("priority", "high");
meta.put("department", "engineering");
meta.put("region", "San Francisco");
meta.put("publisher", pubnub.getConfiguration().getUserId().getValue());
meta.put("requiresAck", true);
Channel channel = pubnub.channel("notifications");
channel.publish(message)
show all 17 lines// Publishing with comprehensive metadata
var message = new {
title = "System Maintenance",
body = "Scheduled maintenance window starting soon",
timestamp = DateTime.UtcNow.ToString("O")
};
Dictionary<string, object> meta = new Dictionary<string, object>
{
{"priority", "high"},
{"department", "engineering"},
{"region", "San Francisco"},
{"publisher", pubnub.PNConfig.UserId},
{"requiresAck", true}
};
show all 19 lines# Publishing with comprehensive metadata
from datetime import datetime
message = {
"title": "System Maintenance",
"body": "Scheduled maintenance window starting soon",
"timestamp": datetime.utcnow().isoformat()
}
meta = {
"priority": "high",
"department": "engineering",
"region": "San Francisco",
"publisher": pubnub.config.user_id,
"requiresAck": True
show all 22 linesIn the above examples, the metadata enables powerful filtering capabilities on the subscriber side. For instance, subscribers could filter for:
- High-priority messages:
meta.priority == "high"
- Department-specific notifications:
meta.department == "engineering"
- Regional content:
meta.region == "San Francisco"
- Messages requiring acknowledgment:
meta.requiresAck == "true"
The metadata fields remain accessible even when message encryption is enabled, making them ideal for routing and filtering while keeping sensitive message content secure.
For complete subscribe filtering documentation and syntax reference, see Subscribe Filter Details.