---
source_url: https://www.pubnub.com/docs/chat/sdks/messages/sending-messages
title: Sending messages (deprecated)
updated_at: 2026-05-20T11:04:41.173Z
---

> Documentation Index
> For a curated overview of PubNub documentation, see: https://www.pubnub.com/docs/llms.txt
> For the full list of all documentation pages, see: https://www.pubnub.com/docs/llms-full.txt


# Sending messages (deprecated)

:::warning Use Chat SDKs
This documentation is deprecated. Use any of our dedicated [Chat SDKs](https://www.pubnub.com/docs/chat/overview) to quickly implement chat functionality in your application.
:::

Messages are the actual packages of data that get published to a [channel](https://www.pubnub.com/docs/chat/sdks/channels/channel-types-names). 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](https://www.pubnub.com/docs/general/messages/publish).

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:

```json
{
  "from": "user123",
  "message": "Hello, how are you?"
}
```

Refer to [Message Specifications](https://www.pubnub.com/docs/general/messages/publish#message-specifications) for more information about messages.

## Sending a message

Use the [publish](https://www.pubnub.com/docs/sdks/javascript/api-reference/publish-and-subscribe#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

```js
pubnub.publish({
  message: 'Hello World!',
  channel: 'ch-1',
}, (status, response) => {
  // handle status, response
});
```

### Swift

```swift
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)")
  }
}
```

### Java

```java
pubNub.publish()
        .message("Hello World!")
        .channel("ch-1")
        .async(result -> { /* check result */ });
```

### Unity

```csharp
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](https://www.pubnub.com/docs/general/messages/receive#add-an-event-handler) for details on how to add a listener.

:::note 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](https://www.pubnub.com/docs/general/setup/users-and-devices#set-the-user-id).
:::

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`.

:::tip 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

```js
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();
  }
});
```

###### Swift

```swift
listener.didReceiveMessage = { message in
  print("Message Received: \(message)")

  let messageDate = message.timetoken.timetokenDate
  print("The message was sent at \(messageDate)")
}
```

###### Java

```java
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());
        Log.d("localDateTime", localDateTime);
    }
});
```

###### Unity

```csharp
pubnub.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
    var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
    DateTime dt = epoch.AddSeconds(mea.MessageResult.Timetoken/10000000);
    DateTime convertedDate = dt.ToLocalTime();
    Debug.Log(convertedDate);
  }
};
```

## Message Events

The following events are generated when messages are received on channels or channel groups that are subscribed by the clients.

```json
{
    "actualChannel": null,
    "channel": "my_channel_1",
    "message": "Hello World!",
    "publisher": "pn-58e1a647-3e8a-4c7f-bfa4-e007ea4b2073",
    "subscribedChannel": "my_channel_1",
    "subscription": null,
    "timetoken": "14966804541029440"
}
```