0
# Connection Information
1
2
Access connection details, statistics, peer addressing information, and real-time connection state monitoring for WebRTC peer connections.
3
4
## Capabilities
5
6
### Connection State Properties
7
8
Access real-time connection state and buffering information.
9
10
```javascript { .api }
11
/**
12
* Whether the peer connection and data channel are ready to use
13
*/
14
peer.connected: boolean;
15
16
/**
17
* Amount of data buffered in the data channel (bytes)
18
*/
19
peer.bufferSize: number;
20
21
/**
22
* Whether the peer has been destroyed and cleaned up
23
*/
24
peer.destroyed: boolean;
25
```
26
27
**Usage Examples:**
28
29
```javascript
30
const peer = new Peer({ initiator: true });
31
32
// Check connection state
33
if (peer.connected) {
34
peer.send('Hello!');
35
} else {
36
console.log('Peer not connected yet');
37
}
38
39
// Monitor buffer size
40
function checkBuffer() {
41
console.log('Buffer size:', peer.bufferSize, 'bytes');
42
if (peer.bufferSize > 32768) { // 32KB
43
console.warn('Buffer getting full - consider waiting');
44
}
45
}
46
47
setInterval(checkBuffer, 1000);
48
49
// Check if peer is destroyed
50
if (peer.destroyed) {
51
console.log('Peer has been destroyed');
52
} else {
53
// Safe to use peer
54
peer.send('Data');
55
}
56
```
57
58
### Address Information
59
60
Access local and remote peer addressing details after connection establishment.
61
62
```javascript { .api }
63
/**
64
* Local peer's IP address (available after connection)
65
*/
66
peer.localAddress: string;
67
68
/**
69
* Local peer's port number (available after connection)
70
*/
71
peer.localPort: number;
72
73
/**
74
* Local peer's IP family ('IPv4' or 'IPv6')
75
*/
76
peer.localFamily: string;
77
78
/**
79
* Remote peer's IP address (available after connection)
80
*/
81
peer.remoteAddress: string;
82
83
/**
84
* Remote peer's port number (available after connection)
85
*/
86
peer.remotePort: number;
87
88
/**
89
* Remote peer's IP family ('IPv4' or 'IPv6')
90
*/
91
peer.remoteFamily: string;
92
93
/**
94
* Get local address information as an object
95
* @returns Address information object
96
*/
97
peer.address(): AddressInfo;
98
99
interface AddressInfo {
100
address: string;
101
family: string;
102
port: number;
103
}
104
```
105
106
**Usage Examples:**
107
108
```javascript
109
const peer = new Peer({ initiator: true });
110
111
peer.on('connect', () => {
112
// Access address information
113
console.log('Local address:', peer.localAddress, ':', peer.localPort);
114
console.log('Local family:', peer.localFamily);
115
console.log('Remote address:', peer.remoteAddress, ':', peer.remotePort);
116
console.log('Remote family:', peer.remoteFamily);
117
118
// Get structured address info
119
const addressInfo = peer.address();
120
console.log('Address info:', addressInfo);
121
// { address: '192.168.1.100', family: 'IPv4', port: 54321 }
122
});
123
124
// Log connection details
125
function logConnectionInfo(peer) {
126
console.log('Connection Info:');
127
console.log(' Local:', `${peer.localFamily} ${peer.localAddress}:${peer.localPort}`);
128
console.log(' Remote:', `${peer.remoteFamily} ${peer.remoteAddress}:${peer.remotePort}`);
129
console.log(' Connected:', peer.connected);
130
console.log(' Buffer size:', peer.bufferSize, 'bytes');
131
}
132
```
133
134
### Connection Statistics
135
136
Retrieve detailed WebRTC connection statistics for monitoring and debugging.
137
138
```javascript { .api }
139
/**
140
* Get connection statistics
141
* @param callback - Callback function receiving error and stats array
142
*/
143
peer.getStats(callback: (err: Error | null, stats: RTCStatsReport[]) => void): void;
144
145
interface RTCStatsReport {
146
id: string;
147
type: string;
148
timestamp: number;
149
[key: string]: any;
150
}
151
```
152
153
**Usage Examples:**
154
155
```javascript
156
const peer = new Peer({ initiator: true });
157
158
peer.on('connect', () => {
159
// Get basic stats
160
peer.getStats((err, reports) => {
161
if (err) {
162
console.error('Failed to get stats:', err);
163
return;
164
}
165
166
console.log('Stats reports:', reports.length);
167
reports.forEach(report => {
168
console.log('Report type:', report.type, 'ID:', report.id);
169
});
170
});
171
172
// Monitor stats periodically
173
setInterval(() => {
174
peer.getStats((err, reports) => {
175
if (err) return;
176
177
// Find candidate pair stats
178
const candidatePairs = reports.filter(r => r.type === 'candidate-pair');
179
candidatePairs.forEach(pair => {
180
if (pair.nominated) {
181
console.log('Active connection:');
182
console.log(' Bytes sent:', pair.bytesSent);
183
console.log(' Bytes received:', pair.bytesReceived);
184
console.log(' Round trip time:', pair.currentRoundTripTime, 'ms');
185
}
186
});
187
188
// Find data channel stats
189
const dataChannels = reports.filter(r => r.type === 'data-channel');
190
dataChannels.forEach(dc => {
191
console.log('Data channel:');
192
console.log(' Messages sent:', dc.messagesSent);
193
console.log(' Messages received:', dc.messagesReceived);
194
console.log(' Bytes sent:', dc.bytesSent);
195
console.log(' Bytes received:', dc.bytesReceived);
196
});
197
});
198
}, 5000);
199
});
200
```
201
202
### State Change Events
203
204
Monitor connection state changes and ICE gathering progress.
205
206
```javascript { .api }
207
// ICE connection state changes
208
peer.on('iceStateChange', (iceConnectionState: string, iceGatheringState: string) => void);
209
210
// WebRTC signaling state changes
211
peer.on('signalingStateChange', (signalingState: string) => void);
212
213
// ICE gathering timeout
214
peer.on('iceTimeout', () => void);
215
216
// Negotiation completed
217
peer.on('negotiated', () => void);
218
```
219
220
**Usage Examples:**
221
222
```javascript
223
const peer = new Peer({ initiator: true });
224
225
// Monitor ICE state
226
peer.on('iceStateChange', (iceConnectionState, iceGatheringState) => {
227
console.log('ICE Connection State:', iceConnectionState);
228
console.log('ICE Gathering State:', iceGatheringState);
229
230
switch (iceConnectionState) {
231
case 'new':
232
console.log('ICE connection starting');
233
break;
234
case 'checking':
235
console.log('ICE connection checking connectivity');
236
break;
237
case 'connected':
238
console.log('ICE connection established');
239
break;
240
case 'completed':
241
console.log('ICE connection completed');
242
break;
243
case 'failed':
244
console.log('ICE connection failed - check network/firewall');
245
break;
246
case 'disconnected':
247
console.log('ICE connection temporarily disconnected');
248
break;
249
case 'closed':
250
console.log('ICE connection closed');
251
break;
252
}
253
});
254
255
// Monitor signaling state
256
peer.on('signalingStateChange', signalingState => {
257
console.log('Signaling State:', signalingState);
258
259
switch (signalingState) {
260
case 'stable':
261
console.log('No ongoing exchange - ready for new negotiation');
262
break;
263
case 'have-local-offer':
264
console.log('Local offer has been applied');
265
break;
266
case 'have-remote-offer':
267
console.log('Remote offer has been applied');
268
break;
269
case 'have-local-pranswer':
270
console.log('Local provisional answer applied');
271
break;
272
case 'have-remote-pranswer':
273
console.log('Remote provisional answer applied');
274
break;
275
case 'closed':
276
console.log('Connection closed');
277
break;
278
}
279
});
280
281
// Handle ICE timeout
282
peer.on('iceTimeout', () => {
283
console.warn('ICE gathering timed out - connection may be slower');
284
});
285
286
// Handle negotiation completion
287
peer.on('negotiated', () => {
288
console.log('Peer connection negotiation completed successfully');
289
});
290
```
291
292
### Connection Monitoring Utilities
293
294
Utility functions for comprehensive connection monitoring and diagnostics.
295
296
**Usage Examples:**
297
298
```javascript
299
// Comprehensive connection monitor
300
class PeerMonitor {
301
constructor(peer) {
302
this.peer = peer;
303
this.startTime = Date.now();
304
this.setupMonitoring();
305
}
306
307
setupMonitoring() {
308
// Log all state changes
309
this.peer.on('iceStateChange', (ice, gathering) => {
310
console.log(`[${this.getElapsed()}] ICE: ${ice}, Gathering: ${gathering}`);
311
});
312
313
this.peer.on('signalingStateChange', state => {
314
console.log(`[${this.getElapsed()}] Signaling: ${state}`);
315
});
316
317
this.peer.on('connect', () => {
318
console.log(`[${this.getElapsed()}] Connected!`);
319
this.logConnectionInfo();
320
this.startStatsMonitoring();
321
});
322
323
this.peer.on('error', err => {
324
console.error(`[${this.getElapsed()}] Error: ${err.code} - ${err.message}`);
325
});
326
}
327
328
getElapsed() {
329
return `${((Date.now() - this.startTime) / 1000).toFixed(1)}s`;
330
}
331
332
logConnectionInfo() {
333
const peer = this.peer;
334
console.log('Connection established:');
335
console.log(` Local: ${peer.localFamily} ${peer.localAddress}:${peer.localPort}`);
336
console.log(` Remote: ${peer.remoteFamily} ${peer.remoteAddress}:${peer.remotePort}`);
337
}
338
339
startStatsMonitoring() {
340
this.statsInterval = setInterval(() => {
341
this.peer.getStats((err, reports) => {
342
if (err) return;
343
344
const stats = this.extractKeyStats(reports);
345
console.log(`[${this.getElapsed()}] Stats:`, stats);
346
});
347
}, 10000); // Every 10 seconds
348
}
349
350
extractKeyStats(reports) {
351
const stats = {
352
bytesSent: 0,
353
bytesReceived: 0,
354
messagesSent: 0,
355
messagesReceived: 0,
356
rtt: null
357
};
358
359
reports.forEach(report => {
360
if (report.type === 'candidate-pair' && report.nominated) {
361
stats.bytesSent += report.bytesSent || 0;
362
stats.bytesReceived += report.bytesReceived || 0;
363
stats.rtt = report.currentRoundTripTime;
364
} else if (report.type === 'data-channel') {
365
stats.messagesSent += report.messagesSent || 0;
366
stats.messagesReceived += report.messagesReceived || 0;
367
}
368
});
369
370
return stats;
371
}
372
373
destroy() {
374
if (this.statsInterval) {
375
clearInterval(this.statsInterval);
376
}
377
}
378
}
379
380
// Usage
381
const peer = new Peer({ initiator: true });
382
const monitor = new PeerMonitor(peer);
383
384
// Clean up when done
385
peer.on('close', () => {
386
monitor.destroy();
387
});
388
```
389
390
### WebRTC Support Detection
391
392
Check for WebRTC support before creating peer connections.
393
394
```javascript { .api }
395
/**
396
* Static property indicating WebRTC support in current environment
397
*/
398
Peer.WEBRTC_SUPPORT: boolean;
399
```
400
401
**Usage Examples:**
402
403
```javascript
404
const Peer = require('simple-peer');
405
406
// Check support before creating peers
407
if (Peer.WEBRTC_SUPPORT) {
408
console.log('WebRTC supported - creating peer');
409
const peer = new Peer({ initiator: true });
410
} else {
411
console.error('WebRTC not supported in this environment');
412
// Fallback to alternative communication method
413
fallbackToWebSocket();
414
}
415
416
// Environment-specific checks
417
function checkWebRTCCapabilities() {
418
console.log('WebRTC Support:', Peer.WEBRTC_SUPPORT);
419
420
if (typeof window !== 'undefined') {
421
// Browser environment
422
console.log('Browser WebRTC APIs:');
423
console.log(' RTCPeerConnection:', !!window.RTCPeerConnection);
424
console.log(' getUserMedia:', !!navigator.mediaDevices?.getUserMedia);
425
console.log(' getDisplayMedia:', !!navigator.mediaDevices?.getDisplayMedia);
426
} else {
427
// Node.js environment
428
console.log('Node.js environment - wrtc package required');
429
}
430
}
431
```