Class: Channel
The Channel
class describes data streams on the connection.
channel.subscribePeers(callback)
This method subscribes to the online
and offline
state of other peers in this channel. It takes in one parameter:
callback
: A callback function that will be called when peers changes.peers
: An array of peers.
The callback function will be invoked when someone joins or leaves this channel.
Example
The following example logs the online peers in the channel:
channel.subscribePeers((peers) => {
peers.forEach((peer) => {
console.log(peer + " is online")
})
});
channel.broadcast(evt, payload)
This method broadcasts my state changes to other peers in this channel with the specified evt
handle. Peers can subscribe to this evt
to observe the payload
. It takes in two parameters:
evt
: The event name.payload
: The payload to be sent.
Broadcast my state changes to other peers in this channel with evt
handle. Peers can subscribe to this evt
to observe the payload
.
Example
The following example broadcasts the document.hidden
state of a user to all other peers in this channel:
const cb = () => {
const state = document.hidden ? 'away' : 'online';
c.broadcast('hidden-state-change', { state });
};
document.addEventListener('visibilitychange', cb)
channel.subscribe(evt, callback)
This method subscribes to state changes with the given event name evt
. It takes in two parameters:
evt
: The event name.callback
: A callback function that will be called when the event is received.payload
: The payload sent by the peer.peerState
: The peer state.
The callback
function will be invoked when another peer broadcasts with the same event name.
Example
The following example subscribes to the hidden-state-change
event from other peers:
channel.subscribe(
'hidden-state-change',
({ payload, peer }) => {
console.log(`${peer.id} change visibility to: ${payload}`)
}
)
By using the Presence
class and joinChannel
, Channel
class and its methods, developers can create real-time web applications with the ability to subscribe to data streams and broadcast data to peers in a secure, low-latency, and high-performance geo-distributed architecture.