Java API & SDK Docs 10.5.8
Breaking changes in v9.0.0
PubNub Java SDK version 9.0.0 unifies the codebases for Java and Kotlin SDKs, introduces a new way of instantiating the PubNub client, and changes asynchronous API callbacks and emitted status events. These changes can impact applications built with previous versions (< 9.0.0
) of the Java SDK.
For more details about what has changed, refer to Java/Kotlin SDK migration guide.
This guide walks you through a simple "Hello, World" application that demonstrates the core concepts of PubNub:
- Setting up a connection
- Sending messages
- Receiving messages in real-time
Overview
This guide helps you get up and running with PubNub in your Java application. The Java software development kit (SDK) provides a simple interface for integrating PubNub real-time messaging. You'll learn how to set up PubNub, configure event listeners, subscribe to channels, and publish messages in a Java environment.
Chat applications
If you want to create a mobile chat application with PubNub, refer to Kotlin Chat SDK for details on all available chat features.
Prerequisites
Before we dive in, make sure you have:
- A basic understanding of Java
- An IDE like IntelliJ IDEA or Eclipse
- Java 8 or later installed
- A PubNub account (we'll help you set this up!)
Setup
Get your PubNub keys
First, get your PubNub keys:
- Sign in or create an account on the PubNub Admin Portal.
- Create an app (or use an existing one).
- Find your publish and subscribe keys in the app dashboard.
When you create an app, PubNub automatically generates a keyset. You can use the same keyset for development and production, but we recommend separate keysets for each environment to improve security and management.
Install the SDK
SDK version
Always use the latest SDK version to have access to the newest features and avoid security vulnerabilities, bugs, and performance issues.
You can install the PubNub Java SDK in several ways:
Maven
Add the following dependency to your pom.xml
:
<dependency>
<groupId>com.pubnub</groupId>
<artifactId>pubnub-gson</artifactId>
<version>10.5.8</version>
</dependency>
Gradle
Add the following to your build.gradle
file:
implementation group: 'com.pubnub', name: 'pubnub-gson', version: '10.5.8'
Source code
Clone the GitHub repository:
git clone https://github.com/pubnub/kotlin
Steps
Initialize PubNub
In your Java application, create a new class (e.g., App.java
) and initialize PubNub.
Make sure to replace the demo keys with your app's publish and subscribe keys from the Admin Portal.
PNConfiguration class in Java
From version 10.0.0 of the Java SDK onward, the correct import for the PNConfiguration
class is com.pubnub.api.java.v2.PNConfiguration
.
For more information, refer to the Configuration section of the SDK documentation.
Set up event listeners
Listeners help the application react to events and messages. You can implement custom app logic to respond to each type of message or event.
There are two main types of listeners you'll need to set up:
- Status listener - for connection state changes and operational events
- Event listener - for messages and presence events
Add listeners to handle connection status and incoming messages:
For more information, refer to the Listeners section of the SDK documentation.
Create a subscription
To receive messages sent to a particular channel, you need to subscribe to it. This allows you to receive messages published to that channel in real time:
You can also subscribe to multiple channels at once using a subscription set:
import java.util.Set;
import java.util.Collections;
import com.pubnub.api.java.v2.subscriptions.SubscriptionSet;
import com.pubnub.api.java.v2.subscriptions.EmptyOptions;
// Create a subscription set with multiple channels
SubscriptionSet subscriptionSet = pubnub.subscriptionSetOf(
Set.of("channel1", "channel2", "channel3"),
Collections.emptySet(),
EmptyOptions.INSTANCE);
// Subscribe to all channels in the set
subscriptionSet.subscribe();
For more information, refer to the Subscribe section of the SDK documentation.
Publish messages
When you publish a message to a channel, PubNub delivers that message to everyone who is subscribed to that channel.
A message can be any type of JavaScript Object Notation (JSON)-serializable data (such as objects, arrays, integers, strings) that is smaller than 32 KiB.
To send a message to a channel, use the publish()
method on your channel object:
You can also publish messages with additional options:
channel.publish(messageJsonObject)
.customMessageType("text-message") // Add a custom message type
.shouldStore(true) // Store the message in history
.meta(metadataObject) // Add metadata for filtering
.async(result -> {
// Handle results
});
For more information, refer to the Publish and Subscribe section of the SDK documentation.
Run the app
To run your Java application:
- Save your complete code in a file like
App.java
. - Compile the file:
javac -cp "path/to/dependencies/*" App.java
. - Run the application:
java -cp ".:path/to/dependencies/*" App
.
You should see output similar to:
PubNub initialized successfully
Subscribed to channel: myChannel
Connected to PubNub
Message to send: {"msg":"Hello World"}
Message successfully published with timetoken: 16789012345678901
Received on channel: myChannel
Received message: {"msg":"Hello World"}
The content of the message is: Hello World
Since you're both publishing and subscribing to the same channel in this example, you'll receive the messages you publish.
Add a delay to prevent the application from exiting immediately:
Complete example
Troubleshooting
If you don't see the expected output, here are some common issues and how to fix them:
Issue | Possible Solutions |
---|---|
No connection message |
|
Message not received |
|
Build errors |
|
Gson deserialization errors |
|
Thread exceptions |
|
More troubleshooting tips
Refer to the Troubleshooting section for more information.
Next steps
Great job! 🎉 You've successfully created your first PubNub Java application. Here are some exciting things you can explore next:
- Advanced features
- Real examples
- More help
- Try out Presence to track online/offline status.
- Implement Message Persistence to store and retrieve messages.
- Use Access Manager to secure your channels.
- Explore Channel Groups to organize your channels.
- Explore our GitHub repository for more code samples.
- Check out the SDK reference documentation for detailed API information.
- Visit the support portal for additional resources.
- Ask the AI assistant (the looking glass icon at the top of the page) for help.