0
# Connection Management
1
2
Low-level connection management with WebSocket handling, automatic reconnection, transport fallback, and connection state monitoring.
3
4
## Capabilities
5
6
### ConnectionManager Class
7
8
Core connection management class handling WebSocket connections and transport strategies.
9
10
```typescript { .api }
11
/**
12
* Manages WebSocket connections with automatic reconnection and fallback
13
* Extends EventsDispatcher for connection state events
14
*/
15
class ConnectionManager extends EventsDispatcher {
16
// Properties
17
key: string;
18
options: ConnectionManagerOptions;
19
state: string;
20
connection: Connection;
21
usingTLS: boolean;
22
timeline: Timeline;
23
socket_id: string;
24
activityTimeout: number;
25
strategy: Strategy;
26
runner: StrategyRunner;
27
28
// Timers
29
unavailableTimer: Timer;
30
activityTimer: Timer;
31
retryTimer: Timer;
32
33
// Configuration
34
activityTimeout: number;
35
strategy: Strategy;
36
runner: StrategyRunner;
37
38
// Callbacks
39
errorCallbacks: ErrorCallbacks;
40
handshakeCallbacks: HandshakeCallbacks;
41
connectionCallbacks: ConnectionCallbacks;
42
43
constructor(key: string, options: ConnectionManagerOptions);
44
45
// Connection Control
46
connect(): void;
47
disconnect(): void;
48
49
// Data Transmission
50
send(data: any): boolean;
51
send_event(name: string, data: any, channel?: string): boolean;
52
53
// State Information
54
isUsingTLS(): boolean;
55
56
// Internal Methods (typically not used directly)
57
tryConnect(): void;
58
abortConnection(): void;
59
clearAllTimeouts(): void;
60
clearTimeout(timer: Timer): void;
61
scheduleConnect(): void;
62
}
63
```
64
65
**Connection Manager Examples:**
66
67
```typescript
68
// Access connection manager from Pusher instance
69
const pusher = new Pusher("app-key", { cluster: "us2" });
70
const connectionManager = pusher.connection;
71
72
// Monitor connection state
73
console.log("Current state:", connectionManager.state);
74
console.log("Socket ID:", connectionManager.socket_id);
75
console.log("Using TLS:", connectionManager.isUsingTLS());
76
77
// Manual connection control (usually automatic)
78
connectionManager.connect();
79
connectionManager.disconnect();
80
81
// Send raw data (usually use higher-level methods)
82
connectionManager.send(JSON.stringify({
83
event: "pusher:ping",
84
data: {}
85
}));
86
87
// Send event through connection
88
connectionManager.send_event("client-event", { message: "hello" }, "my-channel");
89
```
90
91
### Connection Manager Options
92
93
Configuration options for connection management.
94
95
```typescript { .api }
96
/**
97
* Connection manager configuration options
98
*/
99
interface ConnectionManagerOptions {
100
getStrategy: (options: StrategyOptions) => Strategy;
101
timeline: Timeline;
102
activityTimeout: number;
103
pongTimeout: number;
104
unavailableTimeout: number;
105
useTLS: boolean;
106
}
107
108
/**
109
* Strategy options for connection methods
110
*/
111
interface StrategyOptions {
112
useTLS: boolean;
113
hostNonTLS: string;
114
hostTLS: string;
115
httpPort: number;
116
httpsPort: number;
117
wsPort: number;
118
wssPort: number;
119
enableStats: boolean;
120
timelineParams?: any;
121
}
122
```
123
124
### Connection States
125
126
Connection state enumeration and transitions.
127
128
```typescript { .api }
129
// Connection states (string values)
130
type ConnectionState =
131
| "initialized" // Initial state
132
| "connecting" // Attempting to connect
133
| "connected" // Successfully connected
134
| "unavailable" // Service unavailable
135
| "failed" // Connection failed
136
| "disconnected"; // Disconnected
137
138
// State transition events
139
interface StateChangeEvent {
140
previous: ConnectionState;
141
current: ConnectionState;
142
}
143
```
144
145
**Connection State Examples:**
146
147
```typescript
148
const pusher = new Pusher("app-key", { cluster: "us2" });
149
150
// Monitor state changes
151
pusher.connection.bind("state_change", (states) => {
152
console.log(`State changed from ${states.previous} to ${states.current}`);
153
154
switch (states.current) {
155
case "connecting":
156
showConnectingIndicator();
157
break;
158
case "connected":
159
hideConnectingIndicator();
160
console.log("Socket ID:", pusher.connection.socket_id);
161
break;
162
case "disconnected":
163
showOfflineIndicator();
164
break;
165
case "failed":
166
showConnectionFailedError();
167
break;
168
}
169
});
170
171
// Check current state
172
if (pusher.connection.state === "connected") {
173
console.log("Ready to send messages");
174
}
175
```
176
177
### Connection Callbacks
178
179
Callback interfaces for handling connection events.
180
181
```typescript { .api }
182
/**
183
* Error handling callbacks
184
*/
185
interface ErrorCallbacks {
186
tls_only?: () => void;
187
refused?: () => void;
188
backoff?: () => void;
189
retry?: () => void;
190
}
191
192
/**
193
* Handshake event callbacks
194
*/
195
interface HandshakeCallbacks {
196
ssl_only?: () => void;
197
succeeded?: (data: any) => void;
198
failed?: (error: any) => void;
199
}
200
201
/**
202
* Connection event callbacks
203
*/
204
interface ConnectionCallbacks {
205
message?: (event: any) => void;
206
ping?: () => void;
207
pong?: () => void;
208
error?: (error: any) => void;
209
closed?: () => void;
210
}
211
```
212
213
**Callback Examples:**
214
215
```typescript
216
const pusher = new Pusher("app-key", { cluster: "us2" });
217
218
// Connection-level event handling (usually done through pusher.bind)
219
pusher.connection.bind("message", (event) => {
220
console.log("Received message:", event);
221
});
222
223
pusher.connection.bind("error", (error) => {
224
console.error("Connection error:", error);
225
});
226
227
pusher.connection.bind("closed", () => {
228
console.log("Connection closed");
229
});
230
```
231
232
### Transport Configuration
233
234
Transport and strategy configuration for connection fallbacks.
235
236
```typescript { .api }
237
/**
238
* Available transport types
239
*/
240
type Transport =
241
| "ws" // WebSocket
242
| "wss" // Secure WebSocket
243
| "xhr_polling" // XHR long polling
244
| "xhr_streaming" // XHR streaming
245
| "sockjs" // SockJS fallback
246
| "jsonp"; // JSONP polling
247
248
/**
249
* Transport configuration in options
250
*/
251
interface TransportOptions {
252
enabledTransports?: Transport[];
253
disabledTransports?: Transport[];
254
// Timeout configurations
255
activityTimeout?: number; // Activity timeout (default: 120000ms)
256
pongTimeout?: number; // Pong response timeout (default: 30000ms)
257
unavailableTimeout?: number; // Unavailable timeout (default: 10000ms)
258
}
259
```
260
261
**Transport Configuration Examples:**
262
263
```typescript
264
// Enable specific transports only
265
const pusher = new Pusher("app-key", {
266
cluster: "us2",
267
enabledTransports: ["ws", "wss"],
268
disabledTransports: ["xhr_polling", "sockjs"]
269
});
270
271
// Configure timeouts
272
const pusher = new Pusher("app-key", {
273
cluster: "us2",
274
activityTimeout: 30000, // 30 seconds
275
pongTimeout: 6000, // 6 seconds
276
unavailableTimeout: 5000 // 5 seconds
277
});
278
279
// Force specific transport behavior
280
const pusher = new Pusher("app-key", {
281
cluster: "us2",
282
forceTLS: true, // Only use secure transports
283
enabledTransports: ["wss"] // WebSocket Secure only
284
});
285
```
286
287
### Connection Events
288
289
Built-in events for connection state monitoring.
290
291
**Connection State Events:**
292
293
```typescript
294
// Core connection events
295
pusher.connection.bind("connecting", () => {
296
console.log("Attempting to connect...");
297
});
298
299
pusher.connection.bind("connected", () => {
300
console.log("Successfully connected");
301
console.log("Socket ID:", pusher.connection.socket_id);
302
});
303
304
pusher.connection.bind("disconnected", () => {
305
console.log("Disconnected from Pusher");
306
});
307
308
pusher.connection.bind("unavailable", () => {
309
console.log("Pusher service unavailable");
310
});
311
312
pusher.connection.bind("failed", () => {
313
console.log("Connection failed permanently");
314
});
315
316
pusher.connection.bind("reconnecting", () => {
317
console.log("Attempting to reconnect...");
318
});
319
320
pusher.connection.bind("reconnected", () => {
321
console.log("Successfully reconnected");
322
});
323
```
324
325
**Protocol Events:**
326
327
```typescript
328
// Low-level protocol events
329
pusher.connection.bind("message", (event) => {
330
console.log("Raw message received:", event);
331
});
332
333
pusher.connection.bind("ping", () => {
334
console.log("Ping received from server");
335
});
336
337
pusher.connection.bind("pong", () => {
338
console.log("Pong sent to server");
339
});
340
341
pusher.connection.bind("error", (error) => {
342
console.error("Protocol error:", error);
343
});
344
```
345
346
### Advanced Connection Management
347
348
Advanced features for connection monitoring and control.
349
350
```typescript { .api }
351
/**
352
* Timer classes for connection management
353
*/
354
class OneOffTimer {
355
constructor(delay: number, callback: () => void);
356
ensureAborted(): void;
357
}
358
359
class PeriodicTimer {
360
constructor(delay: number, callback: () => void);
361
ensureAborted(): void;
362
}
363
364
/**
365
* Timeline for connection event tracking
366
*/
367
interface TimelineOptions {
368
cluster?: string;
369
features?: string[];
370
params?: any;
371
limit?: number;
372
level?: TimelineLevel;
373
version?: string;
374
}
375
376
class Timeline {
377
constructor(key: string, session: number, options: TimelineOptions);
378
info(event: any): void;
379
debug(event: any): void;
380
warn(event: any): void;
381
error(event: any): void;
382
}
383
```
384
385
**Advanced Usage Examples:**
386
387
```typescript
388
// Custom connection strategy (advanced)
389
const pusher = new Pusher("app-key", {
390
cluster: "us2",
391
// Custom host configuration
392
wsHost: "ws-custom.pusherapp.com",
393
wsPort: 80,
394
wssPort: 443,
395
httpHost: "sockjs-custom.pusherapp.com",
396
httpPort: 80,
397
httpsPort: 443,
398
399
// Enable connection stats
400
enableStats: true,
401
statsHost: "stats.pusherapp.com"
402
});
403
404
// Monitor connection timeline (if enabled)
405
pusher.timeline.info({
406
event: "custom_connection_event",
407
data: { custom: "data" }
408
});
409
410
// Access connection timers (read-only, for monitoring)
411
const connection = pusher.connection;
412
console.log("Activity timer active:", connection.activityTimer !== null);
413
console.log("Retry timer active:", connection.retryTimer !== null);
414
```
415
416
### Network State Detection
417
418
Platform-specific network state detection.
419
420
```typescript { .api }
421
/**
422
* Reachability interface for network detection
423
*/
424
interface Reachability {
425
isOnline(): boolean;
426
bind(event: string, callback: Function): void;
427
unbind(event?: string, callback?: Function): void;
428
}
429
```
430
431
**Network State Examples:**
432
433
```typescript
434
// Network state events (platform-dependent)
435
pusher.bind("online", () => {
436
console.log("Network came online, reconnecting...");
437
});
438
439
pusher.bind("offline", () => {
440
console.log("Network went offline");
441
});
442
443
// Manual network state check (if available)
444
if (typeof navigator !== 'undefined' && navigator.onLine !== undefined) {
445
console.log("Browser online:", navigator.onLine);
446
}
447
```
448
449
## Connection Troubleshooting
450
451
### Common Connection Issues
452
453
```typescript
454
// Enable debug logging
455
Pusher.logToConsole = true;
456
457
// Custom logging for debugging
458
Pusher.log = (message) => {
459
console.log(`[Pusher Debug] ${new Date().toISOString()}:`, message);
460
};
461
462
// Monitor connection attempts
463
let connectionAttempts = 0;
464
pusher.connection.bind("connecting", () => {
465
connectionAttempts++;
466
console.log(`Connection attempt #${connectionAttempts}`);
467
});
468
469
pusher.connection.bind("error", (error) => {
470
console.error("Connection error details:", {
471
error,
472
state: pusher.connection.state,
473
socketId: pusher.connection.socket_id,
474
attempts: connectionAttempts
475
});
476
});
477
478
// Connection health check
479
function checkConnectionHealth() {
480
const state = pusher.connection.state;
481
const socketId = pusher.connection.socket_id;
482
483
return {
484
connected: state === "connected",
485
state,
486
socketId,
487
usingTLS: pusher.connection.isUsingTLS(),
488
timestamp: new Date().toISOString()
489
};
490
}
491
492
// Periodic health monitoring
493
setInterval(() => {
494
console.log("Connection health:", checkConnectionHealth());
495
}, 30000);
496
```
497
498
### Manual Reconnection
499
500
```typescript
501
// Force reconnection
502
function forceReconnect() {
503
console.log("Forcing reconnection...");
504
pusher.disconnect();
505
506
setTimeout(() => {
507
pusher.connect();
508
}, 1000);
509
}
510
511
// Exponential backoff reconnection
512
let reconnectAttempts = 0;
513
pusher.connection.bind("disconnected", () => {
514
const delay = Math.min(1000 * Math.pow(2, reconnectAttempts), 30000);
515
console.log(`Reconnecting in ${delay}ms (attempt ${reconnectAttempts + 1})`);
516
517
setTimeout(() => {
518
reconnectAttempts++;
519
pusher.connect();
520
}, delay);
521
});
522
523
pusher.connection.bind("connected", () => {
524
reconnectAttempts = 0; // Reset on successful connection
525
});
526
```