Install the SDK

To install the SDK, add the following dependency to your build.gradle file:

implementation 'com.pusher:pusher-java-client:2.3.1'

Initialize the SDK

import com.pusher.client.Pusher;
import com.pusher.client.PusherOptions;

PusherOptions options = new PusherOptions()
    .setHost("ws.pulses.cloud")
    .setEncrypted(true);

Pusher pusher = new Pusher("YOUR_APP_KEY", options);

Connect to Pusher

pusher.connect(new ConnectionEventListener() {
    @Override
    public void onConnectionStateChange(ConnectionStateChange change) {
        System.out.println("State changed to " + change.getCurrentState() +
            " from " + change.getPreviousState());
    }

    @Override
    public void onError(String message, String code, Exception e) {
        System.out.println("There was a problem connecting!");
    }
}, ConnectionState.ALL);

Subscribe to a channel

com.pusher.client.channel.Channel channel = pusher.subscribe("channel-name");

Bind to an event

channel.bind("event-name", new SubscriptionEventListener() {
    @Override
    public void onEvent(String channel, String event, String data) {
        System.out.println("Received event with data: " + data);
    }
});

Publish an event from the server

To publish an event from the server, you can use the trigger method. Run the following command:

// First, run 'npm install pusher'
const Pusher = require('pusher');

const pusher = new Pusher('YOUR_APP_KEY', {
    wsHost: 'ws.pulses.cloud',
    encrypted: true,
    disableStats: true,
    enabledTransports: ['ws', 'wss'],
    cluster: 'pulses'
});

pusher.trigger('channel-name', 'event-name', {
    message: 'Hello World'
});

If there isn’t an example in a language that you are familiar with then refer to Pusher’s Channels server libraries page to check if anyone has created one in your language.

Unsubscribe from a channel

pusher.unsubscribe("channel-name");

Disconnect from Pusher

pusher.disconnect();