Sending messages
Messages are the actual packages of data that get published to a channel. Messages can be chat messages, typing on/off events, location updates, emojis, or anything that your application publishes.
For more details on working with messages, refer to Publishing a Message.
The message doesn't have to be formatted as JSON, but it's usually the best choice. Most developers use the JSON format and most PubNub SDKs automatically stringify JSON objects before publishing. Here is an example of a JSON message:
{
"from": "user123",
"message": "Hello, how are you?"
}
Refer to Message Specifications for more information about messages.
Sending a message
Use the publish
method to publish messages in a channel. You can publish a message as a string, or send any data (JSON data, or an object), as long as the data size is below 32 KiB.
- JavaScript
- Swift
- Java
- Unity
pubnub.publish({
message: 'Hello World!',
channel: 'ch-1',
}, (status, response) => {
// handle status, response
});
pubnub.publish(
channel: "ch-1",
message: ["text": "Hello World!"]
) { result in
switch result {
case let .success(response):
print("Successful Publish Response: \(response)")
case let .failure(error):
print("Failed Publish Response: \(error.localizedDescription)")
}
}
pubNub.publish()
.message("Hello World!")
.channel("ch-1")
.async(result -> { /* check result */ });
pubnub.Publish()
.Channel("ch-1")
.Message("Hello World")
.Async((result, status) => {
if (!status.Error) {
Debug.Log(result.Timetoken);
} else {
Debug.Log(status.Error);
Debug.Log(status.ErrorData.Info);
}
});
Receive messages
If users are subscribed to a channel, listener events are triggered in the SDK when a new message is received in that channel. The message includes the publish payload, the sender's User ID and the timetoken of when the message was published. Refer to Add a Listener for details on how to add a listener.
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.
The subscribe listener returns an envelope containing a 17-digit precision Unix time (UTC). To convert the timestamp to a UNIX epoch time (in seconds), divide it by 10,000,000. Or, you can use it directly from 17-digit precision time without converting. The format of localeDateTime
is something similar to 7/5/2019, 3:58:43 PM
.
Don't miss messages
You only receive messages on channels to which you are subscribed. To avoid missing messages, add the message listener before calling subscribe().
- JavaScript
- Swift
- Java
- Unity
pubnub.addListener({
message: (message) => {
// handle message
const channelName = message.channel;
const channelGroup = message.subscription;
const publishTimetoken = message.timetoken;
const msg = message.message;
const publisher = message.publisher;
//show time
const unixTimestamp = message.timetoken / 10000000;
const gmtDate = new Date(unixTimestamp * 1000);
const localeDateTime = gmtDate.toLocaleString();
}
});
listener.didReceiveMessage = { message in
print("Message Received: \(message)")
let messageDate = message.timetoken.timetokenDate
print("The message was sent at \(messageDate)")
}
pubNub.addListener(new EventListener() {
@Override
public void message(PubNub pubnub, PNMessageResult message) {
String channel = message.getChannel(); // the channel for which the message belongs
String channelGroup = message.getSubscription(); // the channel group or wildcard subscription match (if exists)
Long publishTimetoken = message.getTimetoken(); // publish timetoken
JsonElement messagePayload = message.getMessage(); // the message payload
String publisher = message.getPublisher(); // the publisher
//show message time
long timetoken = message.getTimetoken() / 10_000L;
SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy HH:mm:ss");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(timetoken);
String localDateTime = sdf.format(calendar.getTimeInMillis());
show all 18 linespubnub.SubscribeCallback += (sender, e) => {
SubscribeEventEventArgs mea = e as SubscribeEventEventArgs;
if (mea.MessageResult != null) {
Debug.Log("Channel" + mea.MessageResult.Channel); // the channel to which the message belongs
Debug.Log("Payload" + mea.MessageResult.Payload); // the message payload
Debug.Log("Publisher Id: " + mea.MessageResult.IssuingClientId); // the publisher
Debug.Log("Subscription" + mea.MessageResult.Subscription); // the channel group or wildcard subscription match (if exists)
Debug.Log("Timetoken" + mea.MessageResult.Timetoken); // publish timetoken
//show message time
Debug.Log("Channel: " + mea.MessageResult.Channel); // the channel to which the message belongs
Debug.Log("Payload: " + mea.MessageResult.Payload); // the message payload
Debug.Log("Publisher Id: " + mea.MessageResult.IssuingClientId); // the publisher
Debug.Log("Subscription: " + mea.MessageResult.Subscription); // the channel group or wildcard subscription match (if exists)
Debug.Log("Timetoken: " + mea.MessageResult.Timetoken); // publish timetoken
show all 21 linesMessage Events
The following events are generated when messages are received on channels or channel groups that are subscribed by the clients.
{
"actualChannel": null,
"channel": "my_channel_1",
"message": "Hello World!",
"publisher": "pn-58e1a647-3e8a-4c7f-bfa4-e007ea4b2073",
"subscribedChannel": "my_channel_1",
"subscription": null,
"timetoken": "14966804541029440"
}