JavaJava SDK 4.33.3

This page outlines the steps to follow to create a simple Hello, World application with PubNub. This covers the basics of integrating PubNub in your application: setting up a connection to PubNub, and sending and receiving messages.

SDK getting startedSample app quickstart
  1. PubNub account
  2. Download the SDK
  3. Send messages

Sign in or create an account to create an app on the Admin Portal and get the keys to use in your application.

When you create a new app, the first set of keys is generated automatically, but a single app can have as many keysets as you like. We recommend that you create separate keysets for production and test environments.

Download the SDK

Download the SDK from any of the following sources:

Use Maven

To integrate PubNub into your project using Maven, add the following dependency in your pom.xml:

 <dependency>
  <groupId>com.pubnub</groupId>
  <artifactId>pubnub-gson</artifactId>
  <version>4.33.1</version>
</dependency>

Use Gradle

To integrate PubNub into your project using Gradle, add the following dependency in your gradle.build:

compile group: 'com.pubnub', name: 'pubnub-gson', version: '4.33.3'

Use a .jar File

To integrate PubNub into your project using a .jar file, download and copy the PubNub Java archive file into your project's libs directory.

Get the source code

Configure PubNub

In the IDE of your choice, create a new Java project. In that project, create a new App class with the following content. This is the minimum configuration you need to send and receive messages with PubNub.

Make sure to replace myPublishKey and mySubscribeKey with your app's publish and subscribe keys from the Admin Portal.

public static void main(String[] args) {
    PNConfiguration pnConfiguration = new PNConfiguration();
    pnConfiguration.setSubscribeKey("mySubscribeKey");
    pnConfiguration.setPublishKey("myPublishKey");
    pnConfiguration.setUuid("myUniqueUUID");

    PubNub pubnub = new PubNub(pnConfiguration);

For more information, refer to the Configuration section of the SDK documentation.

Listeners help your app react to events and messages. You can implement custom app logic to respond to each type of message or event.

Copy the following code to configure your app such that when it receives an event of type PNConnectedCategory, it calls the publish() function. Additionally, the code below prints out the content of every received message.

pubnub.addListener(new SubscribeCallback() {

    @Override
    public void status(PubNub pubnub, PNStatus status) {
        if (status.getCategory() == PNStatusCategory.PNUnexpectedDisconnectCategory) {
            // This event happens when radio / connectivity is lost
        } else if (status.getCategory() == PNStatusCategory.PNConnectedCategory) {
            // Connect event. You can do stuff like publish, and know you'll get it.
            // Or just use the connected event to confirm you are subscribed for
            // UI / internal notifications, etc
            if (status.getCategory() == PNStatusCategory.PNConnectedCategory) {
                pubnub.publish()
                    .channel(channelName)
                    .message(messageJsonObject)
                    .async((result, publishStatus) -> {
                        if (!publishStatus.isError()) {
                            // Message successfully published to specified channel.
                        }
                        // Request processing failed.
                        else {
                            // Handle message publish error
                            // Check 'category' property to find out
                            // issues because of which the request failed.
                            // Request can be resent using: [status retry];
                        }
                    });
            }
        } else if (status.getCategory() == PNStatusCategory.PNReconnectedCategory) {
            // Happens as part of our regular operation. This event happens when
            // radio / connectivity is lost then regained.
        } else if (status.getCategory() == PNStatusCategory.PNDecryptionErrorCategory) {
            // Handle message decryption error. Probably client configured to
            // encrypt messages and on live data feed it received plain text.
        }
    }

    @Override
    public void message(PubNub pubnub, PNMessageResult message) {
        // Handle new message stored in message.message
        if (message.getChannel() != null) {
            // Message has been received on channel group stored in
            // message.getChannel()
        } else {
            // Message has been received on channel stored in
            // message.getSubscription()
        }

        JsonElement receivedMessageObject = message.getMessage();
        System.out.println("Received message: " + receivedMessageObject.toString());
        // extract desired parts of the payload, using Gson
        String msg = message.getMessage().getAsJsonObject().get("msg").getAsString();
        System.out.println("The content of the message is: " + msg);


        // log the following items with your favorite logger - message.getMessage() -
        // message.getSubscription() - message.getTimetoken()

    }

    // signal, user, space, membership, messageAction, presence, and file
    // listeners have been omitted for reasons of brevity
    // but they are mandatory and you MUST at least provide
    // no op implementations for these listeners

});

For more information, refer to the Listeners section of the SDK documentation.

To receive messages sent to a particular channel, you subscribe to it. When you publish a message to a channel, PubNub delivers that message to everyone subscribed to that channel.

In this app, publishing a message is triggered when the status listener you created in the previous step receives the PNConnectedCategory event. The publish() method uses the channelName and messageJsonObject variables that you can see in the following code.

To subscribe, you send a subscribe() call. It is best to define the channel and the message before you introduce the listeners and send the subscribe call, so make sure to place the relevant code in the appropriate places within the App class.

final String channelName = "myChannel";

// create message payload using Gson
final JsonObject messageJsonObject = new JsonObject();
messageJsonObject.addProperty("msg", "Hello World");

// optionally print the message 
// System.out.println("Message to send: " + messageJsonObject.toString());

pubnub.subscribe()
        .channels(Collections.singletonList(channelName))
        .execute();

For more information, refer to the Publish and Subscribe section of the SDK documentation, and to Publishing a Message.

Your App class should now look similar to the one below:

 import java.util.Collections;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.pubnub.api.PNConfiguration;
import com.pubnub.api.PubNub;
import com.pubnub.api.callbacks.SubscribeCallback;
import com.pubnub.api.enums.PNStatusCategory;
import com.pubnub.api.models.consumer.PNStatus;
import com.pubnub.api.models.consumer.pubsub.PNMessageResult;
import com.pubnub.api.models.consumer.pubsub.PNPresenceEventResult;
import com.pubnub.api.models.consumer.pubsub.PNSignalResult;
import com.pubnub.api.models.consumer.pubsub.message_actions.PNMessageActionResult;
import com.pubnub.api.models.consumer.pubsub.objects.PNMembershipResult;
import com.pubnub.api.models.consumer.pubsub.objects.PNSpaceResult;
import com.pubnub.api.models.consumer.pubsub.objects.PNUserResult;

public class App {
    public static void main(String[] args) {
        PNConfiguration pnConfiguration = new PNConfiguration();
        pnConfiguration.setSubscribeKey("mySubscribeKey");
        pnConfiguration.setPublishKey("myPublishKey");
        pnConfiguration.setUuid("myUniqueUUID");

        PubNub pubnub = new PubNub(pnConfiguration);

        final String channelName = "myChannel";

        // create message payload using Gson
        final JsonObject messageJsonObject = new JsonObject();
        messageJsonObject.addProperty("msg", "Hello World");

        System.out.println("Message to send: " + messageJsonObject.toString());

        pubnub.addListener(new SubscribeCallback() {

            @Override
            public void status(PubNub pubnub, PNStatus status) {
                if (status.getCategory() == PNStatusCategory.PNUnexpectedDisconnectCategory) {
                    // This event happens when radio / connectivity is lost
                } else if (status.getCategory() == PNStatusCategory.PNConnectedCategory) {
                    // Connect event. You can do stuff like publish, and know you'll get it.
                    // Or just use the connected event to confirm you are subscribed for
                    // UI / internal notifications, etc
                    if (status.getCategory() == PNStatusCategory.PNConnectedCategory) {
                        pubnub.publish()
                            .channel(channelName)
                            .message(messageJsonObject)
                            .async((result, publishStatus) -> {
                                if (!publishStatus.isError()) {
                                    // Message successfully published to specified channel.
                                }
                                // Request processing failed.
                                else {
                                    // Handle message publish error. 
                                    // Check 'category' property to find out
                                    // issues because of which the request failed.
                                    // Request can be resent using: [status retry];
                                }
                            });
                    }
                } else if (status.getCategory() == PNStatusCategory.PNReconnectedCategory) {
                    // Happens as part of our regular operation. This event happens when
                    // radio / connectivity is lost, then regained.
                } else if (status.getCategory() == PNStatusCategory.PNDecryptionErrorCategory) {
                    // Handle messsage decryption error. Probably client configured to
                    // encrypt messages and on live data feed it received plain text.
                }
            }

            @Override
            public void message(PubNub pubnub, PNMessageResult message) {
                // Handle new message stored in message.message
                if (message.getChannel() != null) {
                    // Message has been received on channel group stored in
                    // message.getChannel()
                } else {
                    // Message has been received on channel stored in
                    // message.getSubscription()
                }

                JsonElement receivedMessageObject = message.getMessage();
                System.out.println("Received message: " + receivedMessageObject.toString());
                // extract desired parts of the payload, using Gson
                String msg = message.getMessage().getAsJsonObject().get("msg").getAsString();
                System.out.println("The content of the message is: " + msg);

                /*
                 * Log the following items with your favorite logger - message.getMessage() -
                 * message.getSubscription() - message.getTimetoken()
                 */
            }

            @Override
            public void signal(PubNub pubnub, PNSignalResult pnSignalResult) {

            }

            @Override
            public void user(PubNub pubnub, PNUserResult pnUserResult) {

            }

            @Override
            public void space(PubNub pubnub, PNSpaceResult pnSpaceResult) {

            }

            @Override
            public void membership(PubNub pubnub, PNMembershipResult pnMembershipResult) {

            }

            @Override
            public void messageAction(PubNub pubnub, PNMessageActionResult pnMessageActionResult) {

            }

            @Override
            public void presence(PubNub pubnub, PNPresenceEventResult presence) {

            }
        });

        pubnub.subscribe()
        .channels(Collections.singletonList(channelName))
        .execute();
    }
}

Now, run your app to see if you did everything correctly:

Save the App class and run it using the terminal. You can use the one that is built in your IDE or the one that your operating system provides. You should see output similar to the following:

Message to send: {"msg":"Hello World"}
Received message: {"msg":"Hello World"}
The content of the message is: Hello World

Congratulations! You've just subscribed to a channel and sent your first message.

Instead of focusing on the order in which you wrote the code, let's focus on the order in which it runs. The app you just created does a few things:

  • configures a PubNub connection
  • adds the status and message event listeners
  • subscribes to a channel
  • publishes a message

The following code is the minimum configuration you need to send and receive messages with PubNub. For more information, refer to the Configuration section of the SDK documentation.

PNConfiguration pnConfiguration = new PNConfiguration();
pnConfiguration.setSubscribeKey("mySubscribeKey");
pnConfiguration.setPublishKey("myPublishKey");
pnConfiguration.setUuid("myUniqueUUID");

PubNub pubnub = new PubNub(pnConfiguration);

Listeners help your app react to events and messages. You can implement custom app logic to respond to each type of message or event.

You added two listeners to the app: status and message. Status listens for status events and when it receives an event of type PNConnectedCategory, it publishes the message. The other listener, message, listens for incoming messages on a particular channel. When it receives a message, the app simply prints the received message. This is why you see "Hello, World" displayed in the console.

pubnub.addListener(new SubscribeCallback() {

    @Override
    public void status(PubNub pubnub, PNStatus status) {
        if (status.getCategory() == PNStatusCategory.PNUnexpectedDisconnectCategory) {
            // This event happens when radio / connectivity is lost
        } else if (status.getCategory() == PNStatusCategory.PNConnectedCategory) {
            // Connect event. You can do stuff like publish, and know you'll get it.
            // Or just use the connected event to confirm you are subscribed for
            // UI / internal notifications, etc
            if (status.getCategory() == PNStatusCategory.PNConnectedCategory) {
                pubnub.publish()
                    .channel(channelName)
                    .message(messageJsonObject)
                    .async((result, publishStatus) -> {
                        if (!publishStatus.isError()) {
                            // Message successfully published to specified channel.
                        }
                        // Request processing failed.
                        else {
                            // Handle message publish error
                            // Check 'category' property to find out
                            // issues because of which the request failed.
                            // Request can be resent using: [status retry];
                        }
                    });
            }
        } else if (status.getCategory() == PNStatusCategory.PNReconnectedCategory) {
            // Happens as part of our regular operation. This event happens when
            // radio / connectivity is lost then regained.
        } else if (status.getCategory() == PNStatusCategory.PNDecryptionErrorCategory) {
            // Handle message decryption error. Probably client configured to
            // encrypt messages and on live data feed it received plain text.
        }
    }

    @Override
    public void message(PubNub pubnub, PNMessageResult message) {
        // Handle new message stored in message.message
        if (message.getChannel() != null) {
            // Message has been received on channel group stored in
            // message.getChannel()
        } else {
            // Message has been received on channel stored in
            // message.getSubscription()
        }

        JsonElement receivedMessageObject = message.getMessage();
        System.out.println("Received message: " + receivedMessageObject.toString());
        // extract desired parts of the payload, using Gson
        String msg = message.getMessage().getAsJsonObject().get("msg").getAsString();
        System.out.println("The content of the message is: " + msg);


        // log the following items with your favorite logger - message.getMessage() -
        // message.getSubscription() - message.getTimetoken()

    }

    // signal, user, space, membership, messageAction, presence, and file
    // listeners have been omitted for reasons of brevity
    // but they are mandatory and you MUST at least provide
    // no op implementations for these listeners

});

For more information, refer to the Listeners section of the SDK documentation.

PubNub uses the Publish/Subscribe model for realtime communication. This model involves two essential parts:

  • Channels are transient paths over which your data is transmitted
  • Messages contain the data you want to transmit to one or more recipients

When you want to receive messages sent to a particular channel, you subscribe to it. When you publish a message to a channel, PubNub delivers that message to everyone who is subscribed to that channel. In this example, you subscribe to a channel named myChannel.

A message can be any type of JSON-serializable data (such as objects, arrays, integers, strings) that is smaller than 32 KiB. PubNub will, in most cases, deliver your message to its intended recipients in fewer than 100 ms regardless of their location. You can also share files up to 5MB.

When your app successfully connects to a channel, it calls the publish() method, which effectively sends the "Hello World" message. This behavior is configured in the status listener.

if (status.getCategory() == PNStatusCategory.PNConnectedCategory) {
                        pubnub.publish().channel(channelName).message(messageJsonObject).async(new PNCallback<PNPublishResult>(){

You can subscribe to more than one channel with a single subscribe call but in this example, you subscribe to a single channel:

pubnub.subscribe()
        .channels(Collections.singletonList(channelName))
        .execute();

For more information, refer to the Publish and Subscribe section of the SDK documentation, and to Publishing a Message.

You have just learned how to use the Java SDK to send and receive messages using PubNub. Next, take a look at the SDK's reference documentation, which covers PubNub API in more detail.