Send messages
Sending messages is the cornerstone of PubNub. We guarantee that any message you send will be delivered anywhere in the world in under 100ms. This means your messages are literally sent in the blink of an eye.
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.
- JSON
- Plain text
- URL-encoded object
{
"content": {
"type": "text",
"message": "This is a message!"
},
"sender": "Thomas Anderson"
}
"This is a message! Sender: Thomas Anderson"
"%7B%0A%20%20%20%20%22content%22%3A%20%7B%0A%20%20%20%20%20%20%20%20%22
type%22%3A%20%22text%22%2C%0A%20%20%20%20%20%20%20%20%22message%22%3A%
20%22This%20is%20a%20message%21%22%0A%20%20%20%20%7D%2C%0A%20%20%20%20
%22sender%22%3A%20%22Thomas%20Anderson%22%0A%7D"
After sending a message successfully, PubNub servers will send a response including a timetoken, which is an exact timestamp (17 digit value to the nearest 10th nanosecond) of when the message was published. Timetokens are useful if you want to work with historical messages, but we'll talk about this later on.
Depending on your needs, you can structure your payload in different ways, send small bits of data designed for high volumes, or even send a file. If you need an extra layer of security, you might want to consider encrypting your messages and files.
Regardless of what you want to send, you always send it to a channel.
You can think of a channel as a tunnel through which PubNub transmits data from one device to another. When you're sending a message, you must specify a channel to send the message to. You may only send a message to one channel at a time.
In the code below, the message is sent to the channel with the ID of my_channel
.
- JavaScript
- Swift
- Objective-C
- Java
- C#
- Python
- Dart
- Kotlin
pubnub.publish(
{
channel: "my_channel",
message: {"text": "This is my first realtime message!"}
},
function(status, response) {
console.log(status);
console.log(response);
}
);
pubnub.publish(
channel: "my_channel",
message: ["text": "This is my first realtime message!"]
){ result in
switch result {
case let .success(response):
print("succeeded: \(response)")
case let .failure(error):
print("failed: \(error.localizedDescription)")
}
}
[self publish: @{@"text" : @"This is my first realtime message!"} toChannel:@"my_channel"
completion:^(PNPublishStatus *status) {
NSLog(@"%@status '%@'", status);
}];
JsonObject data = new JsonObject();
data.addProperty("text", "This is my first realtime message!");
Channel channel = pubnub.channel("my_channel");
channel.publish(data)
.async(result -> { /* check result */ });
Dictionary<string, string> data = new Dictionary<string, string>();
data.Add("text", "This is my first realtime message!");
pubnub.Publish()
.Channel("my_channel")
.Message(data)
.Execute(new PNPublishResultExt(
(result, status) => {
if (status.isError) {
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, status.error_data.__dict__)
else:
print(result.timetoken)
pubnub.publish()\
.channel("my_channel") \
.message({"text": "This is my first realtime message!"})\
.pn_async(publish_callback)
var result = await pubnub.publish('my_channel', 'This is my first realtime message!');
val channel = pubnub.channel("myChannel")
val myMessage = JsonObject().apply {
addProperty("text", "this is my first realtime message!")
}
channel.publish(myMessage).async { result ->
result.onFailure { exception ->
println("Error while publishing")
exception.printStackTrace()
}.onSuccess { value ->
println("Message sent, timetoken: ${value.timetoken}")
}
}
You don't need to create a channel before you send a message to it. A channel is created automatically when the first message is sent. All you need to do is provide the channel name. Try to be as descriptive as possible and adopt our channel naming convention in order not to miss out on certain PubNub features.
When you've sent your first message, you can check if it's been correctly sent by using the PubNub Debug Console, but now it's only natural to wonder how to receive messages someone else sent. Let's look into that.