Pusher Channels Java Client

repository·master·Indexed 43 days ago

https://github.com/pusher/pusher-websocket-java

A Java client library for Pusher Channels supporting Java SE (8, 11, 17) and Android 7+. Version 2.4.4 provides functionality to connect to Pusher, manage public, private, and presence channels, and handle real-time events via ConnectionEventListener and SubscriptionEventListener.

Tokens
6.1K
Snippets
20
Records
21
Agent score
6%

What's inside Pusher

  1. Handle events with ChannelEventListener and SubscriptionEventListener

    master

    There are two primary ways to handle events:

    1. ChannelEventListener: Used during initial subscription. It handles both protocol-related events (like onSubscriptionSucceeded) and application data events via onEvent. You can specify which event names to listen for when passing this to subscribe.

    2. SubscriptionEventListener: A simpler interface focused solely on application data events. You typically use this by calling channel.bind("event-name", listener) after a channel has been subscribed to.

    To access the payload of an event, call event.getData().

    // Using ChannelEventListener for both protocol and data events
    Channel channel = pusher.subscribe("my-channel", new ChannelEventListener() {
        @Override
        public void onSubscriptionSucceeded(String channelName) {
            System.out.println("Subscribed!");
        }
    
        @Override
        public void onEvent(PusherEvent event) {
            // Called for incoming events named "foo", "bar" or "baz"
        }
    }, "foo", "bar", "baz");
    
    // Using SubscriptionEventListener via bind for specific application events
    channel.bind("my-event", new SubscriptionEventListener() {
        @Override
        public void onEvent(PusherEvent event) {
            // Handle application event
            String data = event.getData();
        }
    });
  2. Use the User object in presence channels

    master

    In presence channels, the User object represents a member. It provides two key methods:

    • getId(): Returns a unique identifier for the user.
    • getInfo(): Returns a JSON string representing arbitrary additional information about the user (e.g., {"user_name":"Mr. User"}).

    You can use libraries like Gson to deserialize the getInfo() string into a Java object.

    // Example deserialization of user info using Gson
    String jsonInfo = user.getInfo();
    Gson gson = new Gson();
    UserInfo info = gson.fromJson(jsonInfo, UserInfo.class);
  3. Install the Pusher Channels Java Client

    master

    You can install the pusher-java-client using Maven or Gradle. The library is available in Maven Central.

    ### Maven
    
    ```xml
    <dependencies>
        <dependency>
          <groupId>com.pusher</groupId>
          <artifactId>pusher-java-client</artifactId>
          <version>2.4.4</version>
        </dependency>
    </dependencies>

    Gradle

    dependencies {
      implementation 'com.pusher:pusher-java-client:2.4.4'
    }
  4. Extract user-id from client events

    master

    When a client triggers a client event, Pusher Channels automatically appends the client's user-id to the message. To verify the authenticity of a client event, extract the ID using getUserId() on the PusherEvent object within your event handler.

    channel.bind("client-my-event", new SubscriptionEventListener() {
        @Override
        public void onEvent(PusherEvent event) {
            System.out.println("Received event with userId: " + event.getUserId());
        }
    });
  5. Handle subscription success and subscription counts

    master

    To be notified when a subscription succeeds, pass an implementation of ChannelEventListener to the subscribe method. To monitor the number of subscribers on a channel, bind to the pusher:subscription_count event using a SubscriptionEventListener.

    // Listen for subscription success
    Channel channel = pusher.subscribe("my-channel", new ChannelEventListener() {
        @Override
        public void onSubscriptionSucceeded(String channelName) {
            System.out.println("Subscribed to channel: " + channelName);
        }
    
        // Other ChannelEventListener methods
    });
    
    // Listen for subscription count events
    channel.bind("pusher:subscription_count", new SubscriptionEventListener() {
        @Override
        public void onEvent(PusherEvent event) {
            System.out.println("Received event with data: " + event.toString());
            System.out.println("Subscription Count is: " + channel.getCount());
        }
    });
  6. Subscribe to public channels

    master

    Public channels allow you to subscribe to data streams identified by a simple name. Subscriptions are preserved across disconnections and re-establishments, so you should only register them once per Pusher instance. You can register them before calling connect().

    Channel channel = pusher.subscribe("my-channel");
  7. Initialize and connect a Pusher instance

    master

    To use Pusher, you must create a Pusher instance using your application key and a PusherOptions object. You then call .connect() to establish the connection.

    Note that if you are using private or presence channels, you must provide a ChannelAuthorizer via PusherOptions to handle authentication.

    // Create a new Pusher instance
    PusherOptions options = new PusherOptions().setCluster("YOUR_APP_CLUSTER");
    Pusher pusher = new Pusher("YOUR_APP_KEY", options);
    
    // Connect to the service
    pusher.connect();
  8. Trigger client events on private or presence channels

    master

    You can trigger events directly from a client on private or presence channels once the subscription has been authorized and has succeeded.

    Rules for Client Events: Events triggered by clients are called 'client events' and must follow these rules:

    • Event names must have a client- prefix.
    • They are subject to rate limits.
    • You can only trigger an event after the subscription has successfully succeeded.

    To ensure safety, always trigger client events within the onSubscriptionSucceeded callback of your channel listener.

    PrivateChannel channel = pusher.subscribePrivate("private-channel",
        new PrivateChannelEventListener() {
            @Override
            public void onSubscriptionSucceeded(String channelName) {
                channel.trigger("client-myEvent", "{\"myName\":\"Bob\"}");
            }
    
            // Other PrivateChannelEventListener methods
        });
  9. Subscribe to private encrypted channels

    master

    Private encrypted channels support end-to-end encryption. You must provide your own authorization endpoint and an encryption master key. When subscribing, you must provide a PrivateEncryptedChannelEventListener and a list of events you are interested in. The listener provides onAuthenticationFailure and onDecryptionFailure (called if a message cannot be decrypted, which triggers a single attempt to refresh the shared secret key from the ChannelAuthorizer).

    PrivateEncryptedChannel privateEncryptedChannel =
    	pusher.subscribePrivateEncrypted("private-encrypted-channel", listener, "my-event");
  10. Subscribe to presence channels

    master

    Presence channels are authorized private channels that expose information about currently subscribed users. Use subscribePresence and implement PresenceChannelEventListener to handle users joining (userSubscribed) or leaving (userUnsubscribed), as well as receiving the initial list of users (onUsersInformationReceived).

    PresenceChannel channel = pusher.subscribePresence("presence-channel",
        new PresenceChannelEventListener() {
            @Override
            public void onUsersInformationReceived(String channelName, Set<User> users) {
                for (User user : users) {
                    userSubscribed(channelName, user);
                }
            }
    
            @Override
            public void userSubscribed(String channelName, User user) {
                System.out.println(
                    String.format("A new user joined channel [%s]: %s, %s",
                                  channelName, user.getId(), user.getInfo())
                );
    
                if (user.equals(channel.getMe())) {
                    System.out.println("me");
                }
            }
    
            @Override
            public void userUnsubscribed(String channelName, User user) {
                System.out.println(
                    String.format("A user left channel [%s]: %s %s",
                                  channelName, user.getId(), user.getInfo())
                );
            }
    
            // Other ChannelEventListener methods
        });
  11. Subscribe to private channels

    master

    Private channels require authorization. You must provide a ChannelAuthorizer (such as the provided HttpChannelAuthorizer) when creating your Pusher instance. Use subscribePrivate to join these channels. If authorization fails, the onAuthenticationFailure method in PrivateChannelEventListener will be triggered.

    // Subscribe to a private channel
    PrivateChannel privateChannel = pusher.subscribePrivate( "private-channel" );
    
    // Handle authentication failures
    PrivateChannel channel = pusher.subscribePrivate("private-channel",
        new PrivateChannelEventListener() {
            @Override
            public void onAuthenticationFailure(String message, Exception e) {
                System.out.println(
                    String.format("Authentication failure due to [%s], exception was [%s]", message, e)
                );
            }
    
            // Other ChannelEventListener methods
        });