0
# Channel Communication
1
2
Channel-based pub/sub messaging system supporting public channels, private authenticated channels, and presence channels with member tracking.
3
4
## Capabilities
5
6
### Channel Subscription
7
8
Subscribe to and manage channels for receiving real-time messages.
9
10
```typescript { .api }
11
/**
12
* Subscribe to a channel
13
* @param channel_name - Name of the channel to subscribe to
14
* @returns Channel instance for event binding
15
*/
16
subscribe(channel_name: string): Channel;
17
18
/**
19
* Unsubscribe from a channel
20
* @param channel_name - Name of the channel to unsubscribe from
21
*/
22
unsubscribe(channel_name: string): void;
23
24
/**
25
* Get a channel by name (must be already subscribed)
26
* @param name - Name of the channel
27
* @returns Channel instance or null if not found
28
*/
29
channel(name: string): Channel;
30
31
/**
32
* Get all subscribed channels
33
* @returns Array of all Channel instances
34
*/
35
allChannels(): Channel[];
36
```
37
38
**Subscription Examples:**
39
40
```typescript
41
// Subscribe to public channel
42
const publicChannel = pusher.subscribe("news-updates");
43
44
// Subscribe to private channel (requires authentication)
45
const privateChannel = pusher.subscribe("private-user-123");
46
47
// Subscribe to presence channel (requires authentication + user info)
48
const presenceChannel = pusher.subscribe("presence-chat-room");
49
50
// Get existing channel
51
const channel = pusher.channel("news-updates");
52
53
// Get all channels
54
const channels = pusher.allChannels();
55
console.log(`Subscribed to ${channels.length} channels`);
56
57
// Unsubscribe
58
pusher.unsubscribe("news-updates");
59
```
60
61
### Channel Class
62
63
Base channel class for pub/sub messaging and event handling.
64
65
```typescript { .api }
66
/**
67
* Base channel class for pub/sub messaging
68
* Extends EventsDispatcher for event binding capabilities
69
*/
70
class Channel extends EventsDispatcher {
71
// Properties
72
name: string;
73
pusher: Pusher;
74
subscribed: boolean;
75
subscriptionPending: boolean;
76
subscriptionCancelled: boolean;
77
subscriptionCount: null;
78
79
constructor(name: string, pusher: Pusher);
80
81
// Event Binding
82
bind(event: string, callback: Function, context?: any): Channel;
83
unbind(event?: string, callback?: Function, context?: any): Channel;
84
bind_global(callback: Function): Channel;
85
unbind_global(callback?: Function): Channel;
86
unbind_all(): Channel;
87
88
// Client Events
89
trigger(event: string, data: any): boolean;
90
91
// Subscription Management
92
subscribe(): void;
93
unsubscribe(): void;
94
cancelSubscription(): void;
95
reinstateSubscription(): void;
96
disconnect(): void;
97
98
// Authorization (overridden in subclasses)
99
authorize(socketId: string, callback: ChannelAuthorizationCallback): void;
100
}
101
```
102
103
**Channel Usage Examples:**
104
105
```typescript
106
const channel = pusher.subscribe("my-channel");
107
108
// Bind to specific events
109
channel.bind("new-message", (data) => {
110
console.log("New message:", data.message);
111
});
112
113
channel.bind("user-joined", (data) => {
114
console.log(`${data.username} joined`);
115
});
116
117
// Bind to all events on this channel
118
channel.bind_global((event, data) => {
119
console.log(`Channel event: ${event}`, data);
120
});
121
122
// Trigger client events (requires client event permissions)
123
channel.trigger("client-typing", {
124
user: "alice",
125
typing: true
126
});
127
128
// Unbind specific events
129
channel.unbind("new-message", messageHandler);
130
131
// Unbind all events
132
channel.unbind_all();
133
```
134
135
### PrivateChannel Class
136
137
Private channel requiring authentication for subscription.
138
139
```typescript { .api }
140
/**
141
* Private channel requiring authentication
142
* Extends Channel with authorization capabilities
143
*/
144
class PrivateChannel extends Channel {
145
constructor(name: string, pusher: Pusher);
146
147
// Override Channel authorization with actual auth logic
148
authorize(socketId: string, callback: ChannelAuthorizationCallback): void;
149
}
150
```
151
152
**Private Channel Examples:**
153
154
```typescript
155
const privateChannel = pusher.subscribe("private-user-messages");
156
157
// Same API as regular channels, but requires authentication
158
privateChannel.bind("new-message", (data) => {
159
console.log("Private message:", data);
160
});
161
162
// Authentication handled automatically during subscription
163
privateChannel.bind("pusher:subscription_succeeded", () => {
164
console.log("Successfully authenticated to private channel");
165
});
166
167
privateChannel.bind("pusher:subscription_error", (error) => {
168
console.error("Failed to authenticate:", error);
169
});
170
```
171
172
### PresenceChannel Class
173
174
Extended channel with member presence tracking capabilities.
175
176
```typescript { .api }
177
/**
178
* Presence channel with member tracking
179
* Extends PrivateChannel (which extends Channel)
180
*/
181
class PresenceChannel extends PrivateChannel {
182
members: Members;
183
184
constructor(name: string, pusher: Pusher);
185
186
// Inherited from Channel + PrivateChannel
187
// Plus presence-specific authorization
188
authorize(socketId: string, callback: Function): void;
189
}
190
```
191
192
**Presence Channel Examples:**
193
194
```typescript
195
const presenceChannel = pusher.subscribe("presence-chat-room") as PresenceChannel;
196
197
// Access member information
198
console.log(`${presenceChannel.members.count} users online`);
199
console.log("My ID:", presenceChannel.members.myID);
200
console.log("My data:", presenceChannel.members.me);
201
202
// Iterate over all members
203
presenceChannel.members.each((member) => {
204
console.log("Member:", member);
205
});
206
207
// Get specific member
208
const user = presenceChannel.members.get("user-123");
209
210
// Presence events
211
presenceChannel.bind("pusher:subscription_succeeded", (members) => {
212
console.log("Joined presence channel with members:", members);
213
});
214
215
presenceChannel.bind("pusher:member_added", (member) => {
216
console.log("Member joined:", member);
217
});
218
219
presenceChannel.bind("pusher:member_removed", (member) => {
220
console.log("Member left:", member);
221
});
222
```
223
224
### Members Class
225
226
Manages the member list for presence channels.
227
228
```typescript { .api }
229
/**
230
* Manages presence channel member list
231
*/
232
class Members {
233
members: any; // Object containing member data
234
count: number; // Number of members
235
myID: any; // Current user's ID
236
me: any; // Current user's data
237
238
constructor();
239
240
/**
241
* Get member by ID
242
* @param id - Member ID to retrieve
243
* @returns Member data or undefined
244
*/
245
get(id: string): any;
246
247
/**
248
* Iterate over all members
249
* @param callback - Function called for each member
250
*/
251
each(callback: Function): void;
252
253
/**
254
* Set current user's ID
255
* @param id - User ID to set
256
*/
257
setMyID(id: string): void;
258
259
// Internal methods (not typically used directly)
260
onSubscription(subscriptionData: any): void;
261
addMember(memberData: any): any;
262
removeMember(memberData: any): any;
263
reset(): void;
264
}
265
```
266
267
**Members Usage Examples:**
268
269
```typescript
270
const presenceChannel = pusher.subscribe("presence-lobby") as PresenceChannel;
271
const members = presenceChannel.members;
272
273
// Check member count
274
if (members.count > 10) {
275
console.log("Lobby is getting crowded!");
276
}
277
278
// Get current user info
279
console.log("I am:", members.me);
280
281
// Find specific member
282
const admin = members.get("admin-user-id");
283
if (admin) {
284
console.log("Admin is online:", admin);
285
}
286
287
// List all members
288
members.each((member) => {
289
console.log(`Member ${member.id}: ${member.info.name}`);
290
});
291
```
292
293
### Channel Types and Naming
294
295
Different channel types have specific naming conventions and behaviors:
296
297
```typescript { .api }
298
// Channel type examples
299
type ChannelName =
300
| string // Public channel: "news", "updates"
301
| `private-${string}` // Private channel: "private-user-123"
302
| `presence-${string}`; // Presence channel: "presence-chat-room"
303
```
304
305
**Channel Type Examples:**
306
307
```typescript
308
// Public channels (no authentication required)
309
const news = pusher.subscribe("news-feed");
310
const alerts = pusher.subscribe("system-alerts");
311
312
// Private channels (authentication required)
313
const userChannel = pusher.subscribe("private-user-456");
314
const adminChannel = pusher.subscribe("private-admin-panel");
315
316
// Presence channels (authentication + user info required)
317
const chatRoom = pusher.subscribe("presence-general-chat");
318
const gameRoom = pusher.subscribe("presence-game-lobby-1");
319
```
320
321
## Built-in Channel Events
322
323
### Subscription Events
324
325
- `pusher:subscription_succeeded` - Successfully subscribed to channel
326
- `pusher:subscription_error` - Failed to subscribe (auth failure, etc.)
327
- `pusher:subscription_count` - Channel subscription count update
328
329
### Presence Events (Presence Channels Only)
330
331
- `pusher:member_added` - New member joined the presence channel
332
- `pusher:member_removed` - Member left the presence channel
333
334
### Error Events
335
336
- `pusher:error` - Channel-specific error occurred
337
338
## Channel Event Data
339
340
### Subscription Success Data
341
342
```typescript { .api }
343
// Public channel subscription
344
interface SubscriptionSucceededData {
345
// No additional data for public channels
346
}
347
348
// Presence channel subscription
349
interface PresenceSubscriptionData {
350
presence: {
351
count: number;
352
ids: string[];
353
hash: { [id: string]: any };
354
};
355
}
356
```
357
358
### Member Events Data
359
360
```typescript { .api }
361
interface MemberEventData {
362
id: string;
363
info: any; // User-defined member information
364
}
365
```
366
367
**Event Data Examples:**
368
369
```typescript
370
// Subscription succeeded
371
channel.bind("pusher:subscription_succeeded", (data) => {
372
console.log("Subscribed successfully", data);
373
});
374
375
// Presence subscription with member data
376
presenceChannel.bind("pusher:subscription_succeeded", (data) => {
377
console.log(`Joined with ${data.presence.count} members`);
378
console.log("Member IDs:", data.presence.ids);
379
console.log("Member data:", data.presence.hash);
380
});
381
382
// Member events
383
presenceChannel.bind("pusher:member_added", (member) => {
384
console.log(`${member.info.name} (${member.id}) joined`);
385
});
386
387
presenceChannel.bind("pusher:member_removed", (member) => {
388
console.log(`${member.info.name} (${member.id}) left`);
389
});
390
```