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

Pub Sub System

Roman Baitaliuk edited this page Jan 20, 2018 · 5 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.

func onConnect() {
    /**
        Subscribe to the channel (can be any channels you want)
    */
    let channel = webSocket.subscribe("any-channel-name")

    /**
        Listen on messages in that channel
    */
    channel.watch { (data) in
        // execute code when receive any messages on the channel
    }

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

    /**
        Unsubscribe from the channel
    */
    channel.unsubscribe()
}
    
func onDisconnect(code: Int?, reason: String?) {
        
}
    
func onError(error: Error) {
        
}

also you can chain everything in one expression

func onConnect() {
    let channel = webSocket.subscribe("any-channel-name").watch { (data) in
        // execute code when receive any messages on the channel
    }.publish(data: "any-data-you-want")
}

func onDisconnect(code: Int?, reason: String?) {
        
}
    
func onError(error: Error) {
        
}

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

webSocket.getChannel(by: 'channel-name')

/**
    You can get an array of all subscribed channels
*/
let channels = webSocket.getChannels()

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.

Clone this wiki locally