Managing Channels
Messages are always sent through PubNub on a Channel. You don't have to define channels in advance; the act of publishing a message creates the channel if it doesn't already exist.
PubNub supports an unlimited number of channels. A channel name can be any alphanumeric string up to 92 characters. There are a few invalid characters, and some that are reserved for special features. Learn more in the Channels section.
Some common uses of channels are to carry direct messages, group chats, broadcasts, fan-in message patterns, and more. For an overview of common channel configurations, refer to Channel Topology.
This section provides an overview of the following concepts related to channels:
- Managing subscriptions to channels and channel groups
- Managing metadata about your channels and users
- Managing membership data for your users and channels
Channel Subscriptions
Users can subscribe to channels and begin listening for messages on a single socket connection. You can subscribe to a list of up to 100 channels, or use channel groups to subscribe to the list of channels in a channel group.
Subscribing to channels initiates a realtime connection with PubNub. This connection stays open as long as the user remains subscribed from a client application. Any user subscribing to a channel receives messages in under 100ms, regardless of which global region the message was published in.
Subscriptions vs memberships
A subscription isn't the same as a membership: subscriptions allow you to send and receive messages on channels, whereas memberships are metadata about the relationship between users and channels.
The following code samples show a client subscribing to a single channel called chats.room1
.
pubnub.subscribe({channels: ["chats.room1"]});
pubnub.subscribe(to: ["chats.room1"])
[self.pubnub subscribeToChannels: @[@"chats.room1"] withPresence:NO];
pubnub.subscribe().channels(Arrays.asList("chats.room1"));
pubnub.Subscribe()
.Channels(new List<string>() {
"chats.room1"
})
.Execute();
Subscription types
There are a few ways to subscribe to channels:
- Subscribe to a single channel
- Use a multiplex subscription to subscribe to up to 100 channels in a single subscribe call
- Subscribe to a channel group to bundle large numbers of channels into a group that can be identified by name
- Use wildcards to subscribe to a hierarchical list of channels
- Filter your subscriptions to only receive the messages you want
Typically, you subscribe to channels on app load. As a user moves around in the app, they stay subscribed to their list of channels so they can continue to receive messages on all their channels.
For more details on working with subscriptions, refer to Subscribe to a Channel.
Channel Metadata
Clients can optionally store channel metadata such as a channel name and description. You can also use a custom field to store additional data. Some examples of custom data include a channel's type, purpose, or owner.
PubNub generates channel metadata events when a user metadata is set or deleted. Clients can add Objects Listeners to receive these events.
Here is a simple example of adding metadata to a channel:
pubnub.objects.setChannelMetadata({
channel: "my_channel",
data: {
name: "main channel",
description: "This channel is for company wide chatter.",
custom: {
"owner": "johndoe_1"
}
}
});
let ch = PubNubChannelMetadataBase(
id: "my_channel", name: "main channel",
custom: ["owner": "johndoe_1"]
)
pubnub.set(channel: ch) { result in
switch result {
case let .success(channelMetadata):
print("The metadata for `\(channelMetadata.metadataId)`: \(channelMetadata)")
case let .failure(error):
print("Create request failed with error: \(error.localized### Description)")
}
}
self.client.objects().setChannelMetadata(@"my_channel")
.name(@"main channel")
.information(@"This channel is for company wide chatter.")
.custom(@{ @"owner": @"johndoe_1" })
.includeFields(PNChannelCustomField)
.performWithCompletion(^(PNSetChannelMetadataStatus *status) {
if (!status.isError) {
/**
* Channel metadata successfully has been set.
* Channel metadata information available here: status.data.metadata
*/
} else {
/**
* Handle channel metadata update error. Check 'category' property to find out possible
* issue because of which request did fail.
*
* Request can be resent using: [status retry]
*/
}
});
Map<String, Object> custom = new HashMap<>();
custom.put("owner", "johndoe_1");
pubnub.setChannelMetadata()
.channel("my_channel")
.name("main channel")
.description("This channel is for company wide chatter.")
.custom(custom)
.includeCustom(true)
.async(new PNCallback<PNSetChannelMetadataResult>() {
@Override
public void onResponse(@Nullable final PNSetChannelMetadataResult result, @NotNull final PNStatus status) {
if (status.isError()) {
//handle error
} else {
//handle result
}
}
});
PNResult<PNSetChannelMetadataResult> setChannelMetadataResponse = await pubnub.SetChannelMetadata()
.Channel("my_channel")
.Name("main channel")
.Description("This channel is for company wide chatter.")
.Custom(new Dictionary<string, object>() { { "owner", "johndoe_1" } })
.IncludeCustom(true)
.ExecuteAsync();
PNSetChannelMetadataResult setChannelMetadataResult = setChannelMetadataResponse.Result;
PNStatus status = setChannelMetadataResponse.Status;
Sample channel metadata event:
{
"channel":"ch-1",
"message":{
"event":"set",
"type":"channel",
"data":{
"id":"ch-1",
"name":"main channel",
"description":"A meeting room for the team",
"updated":"2020-02-20T23:11:20.893755"
}
},
"subscription":null,
"timetoken":"15119446002445794"
}
Refer to Channel Metadata to learn more about working with channel metadata.