Skip to content
This repository has been archived by the owner on Nov 2, 2020. It is now read-only.

Pub Sub System

Egor Egorov edited this page Jan 5, 2018 · 3 revisions

ClusterWS Pub/Sub system is the only way to communicate between different clients client <-> client communication. In this documentation we will show the only functionality of Pub/Sub system for more examples of client <-> client communication check Client to Client Communication guide.

Channel channel

socket.setClusterWSListener(new IClusterWSListener() {
    @Override
    public void onConnected() {
        // Subscribe to the channel (can be any channels you want)
        channel = socket.subscribe("any-channel-name");

        // Listen on messages in that channel
        channel.watch(new Channel.IChannelListener() {
            @Override
            public void onDataReceived(String channelName, Object data) {
                // Execute code when receive any messages on the channel
            }
        });

        // Publish any message you want
        channel.publish("any-data-you-want");

        // Unsubscribe from the channel
        channel.unsubscribe();
    }

    @Override
    public void onError(Exception exception) {

    }

    @Override
    public void onDisconnected(int code, String reason) {

    }
});

also you can chain everything if you want

socket.setClusterWSListener(new IClusterWSListener() {
    @Override
    public void onConnected() {
        // Subscribe to the channel (can be any channels you want)
        socket.subscribe("any-channel-name").watch(new Channel.IChannelListener() {
            @Override
            public void onDataReceived(String channelName, Object data) {
                // Execute code when receive any messages on the channel
            }
        }).publish("any-data-you-want");

    }

    @Override
    public void onError(Exception exception) {

    }

    @Override
    public void onDisconnected(int code, String reason) {

    }
});

in case if you want to get the channel from the socket (must be subscribed before) you can use getChannelByName method

Channel channel = socket.getChannelByName("channel-name");
channel.publish("message-to-that-channel");

Note: You can subscribe to the channels only if a socket is connected to the server (not before that). You can subscribe on connect event or on any other events you emit from the server.