0
# Network Transport
1
2
Low-level transport layer including ICE connectivity establishment, DTLS security, and SCTP association management for reliable data delivery.
3
4
## Capabilities
5
6
### RTCIceTransport Class
7
8
Manages ICE (Interactive Connectivity Establishment) connectivity between peers.
9
10
```python { .api }
11
class RTCIceTransport:
12
"""ICE transport for peer connectivity establishment."""
13
14
@property
15
def iceGatherer(self) -> RTCIceGatherer:
16
"""Associated ICE gatherer"""
17
18
@property
19
def role(self) -> str:
20
"""ICE role: "controlling" or "controlled" """
21
22
@property
23
def state(self) -> str:
24
"""Transport state: "new", "checking", "connected", "completed", "failed", "disconnected", "closed" """
25
26
def addRemoteCandidate(self, candidate: RTCIceCandidate) -> None:
27
"""
28
Add a remote ICE candidate.
29
30
Parameters:
31
- candidate (RTCIceCandidate): Remote candidate to add
32
"""
33
34
def getRemoteCandidates(self) -> list:
35
"""
36
Get list of remote ICE candidates.
37
38
Returns:
39
list: List of RTCIceCandidate objects
40
"""
41
42
async def start(self, remoteParameters: RTCIceParameters) -> None:
43
"""
44
Start ICE connectivity checks.
45
46
Parameters:
47
- remoteParameters (RTCIceParameters): Remote ICE parameters
48
"""
49
50
async def stop(self) -> None:
51
"""Stop ICE transport"""
52
```
53
54
### RTCIceGatherer Class
55
56
Gathers local ICE candidates for connectivity establishment.
57
58
```python { .api }
59
class RTCIceGatherer:
60
"""ICE candidate gatherer."""
61
62
@property
63
def state(self) -> str:
64
"""Gathering state: "new", "gathering", "complete" """
65
66
async def gather(self, iceServers=None) -> None:
67
"""
68
Gather ICE candidates.
69
70
Parameters:
71
- iceServers (list, optional): List of RTCIceServer objects
72
"""
73
74
def getDefaultIceServers(self) -> list:
75
"""
76
Get default STUN servers.
77
78
Returns:
79
list: List of default RTCIceServer objects
80
"""
81
82
def getLocalCandidates(self) -> list:
83
"""
84
Get gathered local candidates.
85
86
Returns:
87
list: List of RTCIceCandidate objects
88
"""
89
90
def getLocalParameters(self) -> RTCIceParameters:
91
"""
92
Get local ICE parameters.
93
94
Returns:
95
RTCIceParameters: Local ICE username fragment and password
96
"""
97
```
98
99
### RTCDtlsTransport Class
100
101
Provides DTLS (Datagram Transport Layer Security) encryption over ICE transport.
102
103
```python { .api }
104
class RTCDtlsTransport:
105
"""DTLS transport for secure communication."""
106
107
@property
108
def state(self) -> str:
109
"""Transport state: "new", "connecting", "connected", "closed", "failed" """
110
111
@property
112
def transport(self) -> RTCIceTransport:
113
"""Associated ICE transport"""
114
115
def getLocalParameters(self) -> RTCDtlsParameters:
116
"""
117
Get local DTLS parameters.
118
119
Returns:
120
RTCDtlsParameters: Local DTLS fingerprints and role
121
"""
122
123
async def start(self, remoteParameters: RTCDtlsParameters) -> None:
124
"""
125
Start DTLS handshake.
126
127
Parameters:
128
- remoteParameters (RTCDtlsParameters): Remote DTLS parameters
129
"""
130
131
async def stop(self) -> None:
132
"""Stop DTLS transport"""
133
```
134
135
### RTCSctpTransport Class
136
137
SCTP (Stream Control Transmission Protocol) transport for data channels.
138
139
```python { .api }
140
class RTCSctpTransport:
141
"""SCTP transport for data channels."""
142
143
@property
144
def is_server(self) -> bool:
145
"""Whether transport acts as SCTP server"""
146
147
@property
148
def maxChannels(self) -> int:
149
"""Maximum number of simultaneous data channels"""
150
151
@property
152
def port(self) -> int:
153
"""Local SCTP port"""
154
155
@property
156
def state(self) -> str:
157
"""Transport state: "connecting", "connected", "closed" """
158
159
@property
160
def transport(self) -> RTCDtlsTransport:
161
"""Associated DTLS transport"""
162
163
@classmethod
164
def getCapabilities(cls) -> RTCSctpCapabilities:
165
"""
166
Get SCTP capabilities.
167
168
Returns:
169
RTCSctpCapabilities: Maximum message size
170
"""
171
172
async def start(self, remoteCaps: RTCSctpCapabilities, remotePort: int = None) -> None:
173
"""
174
Start SCTP association.
175
176
Parameters:
177
- remoteCaps (RTCSctpCapabilities): Remote SCTP capabilities
178
- remotePort (int, optional): Remote SCTP port
179
"""
180
181
async def stop(self) -> None:
182
"""Stop SCTP transport"""
183
```
184
185
### Transport Parameters and Data Types
186
187
Configuration objects for transport establishment.
188
189
```python { .api }
190
class RTCIceCandidate:
191
"""ICE candidate information."""
192
193
def __init__(self, candidate: str, sdpMid: str = None, sdpMLineIndex: int = None):
194
"""
195
Create ICE candidate.
196
197
Parameters:
198
- candidate (str): Candidate string
199
- sdpMid (str, optional): Media identifier
200
- sdpMLineIndex (int, optional): Media line index
201
"""
202
203
@property
204
def candidate(self) -> str:
205
"""Candidate string"""
206
207
@property
208
def sdpMid(self) -> str:
209
"""Media identifier"""
210
211
@property
212
def sdpMLineIndex(self) -> int:
213
"""Media line index"""
214
215
class RTCIceParameters:
216
"""ICE connection parameters."""
217
218
@property
219
def usernameFragment(self) -> str:
220
"""ICE username fragment"""
221
222
@property
223
def password(self) -> str:
224
"""ICE password"""
225
226
class RTCDtlsParameters:
227
"""DTLS connection parameters."""
228
229
@property
230
def fingerprints(self) -> list:
231
"""List of RTCDtlsFingerprint objects"""
232
233
@property
234
def role(self) -> str:
235
"""DTLS role: "client" or "server" """
236
237
class RTCDtlsFingerprint:
238
"""DTLS certificate fingerprint."""
239
240
@property
241
def algorithm(self) -> str:
242
"""Hash algorithm (e.g., "sha-256")"""
243
244
@property
245
def value(self) -> str:
246
"""Fingerprint value"""
247
248
class RTCSctpCapabilities:
249
"""SCTP transport capabilities."""
250
251
@property
252
def maxMessageSize(self) -> int:
253
"""Maximum message size in bytes"""
254
```
255
256
## Usage Examples
257
258
### ICE Transport Setup
259
260
```python
261
import aiortc
262
import asyncio
263
264
async def ice_transport_setup():
265
# Create ICE gatherer
266
gatherer = aiortc.RTCIceGatherer()
267
268
# Get default STUN servers
269
default_servers = gatherer.getDefaultIceServers()
270
print(f"Default STUN servers: {[server.urls for server in default_servers]}")
271
272
# Add custom STUN/TURN servers
273
ice_servers = [
274
aiortc.RTCIceServer("stun:stun.l.google.com:19302"),
275
aiortc.RTCIceServer(
276
"turn:turnserver.example.com:3478",
277
username="user",
278
credential="pass"
279
)
280
]
281
282
# Start gathering candidates
283
await gatherer.gather(ice_servers)
284
285
# Get local parameters
286
local_params = gatherer.getLocalParameters()
287
print(f"Local ICE parameters: {local_params.usernameFragment}")
288
289
# Get gathered candidates
290
local_candidates = gatherer.getLocalCandidates()
291
print(f"Gathered {len(local_candidates)} candidates")
292
293
for candidate in local_candidates:
294
print(f" {candidate.candidate}")
295
296
# Create ICE transport
297
ice_transport = aiortc.RTCIceTransport(gatherer)
298
print(f"ICE transport state: {ice_transport.state}")
299
```
300
301
### DTLS Transport Security
302
303
```python
304
async def dtls_transport_setup():
305
# Create ICE transport first
306
gatherer = aiortc.RTCIceGatherer()
307
await gatherer.gather()
308
ice_transport = aiortc.RTCIceTransport(gatherer)
309
310
# Create DTLS transport over ICE
311
dtls_transport = aiortc.RTCDtlsTransport(ice_transport)
312
313
# Get local DTLS parameters
314
local_dtls_params = dtls_transport.getLocalParameters()
315
print(f"DTLS role: {local_dtls_params.role}")
316
print("DTLS fingerprints:")
317
for fp in local_dtls_params.fingerprints:
318
print(f" {fp.algorithm}: {fp.value}")
319
320
# Monitor transport state
321
@dtls_transport.on("statechange")
322
def on_state_change():
323
print(f"DTLS state changed to: {dtls_transport.state}")
324
325
print(f"Initial DTLS state: {dtls_transport.state}")
326
```
327
328
### SCTP Data Transport
329
330
```python
331
async def sctp_transport_setup():
332
# Create DTLS transport (simplified setup)
333
gatherer = aiortc.RTCIceGatherer()
334
await gatherer.gather()
335
ice_transport = aiortc.RTCIceTransport(gatherer)
336
dtls_transport = aiortc.RTCDtlsTransport(ice_transport)
337
338
# Create SCTP transport over DTLS
339
sctp_transport = aiortc.RTCSctpTransport(dtls_transport)
340
341
# Get SCTP capabilities
342
capabilities = aiortc.RTCSctpTransport.getCapabilities()
343
print(f"Max SCTP message size: {capabilities.maxMessageSize} bytes")
344
345
# Monitor SCTP transport
346
print(f"SCTP port: {sctp_transport.port}")
347
print(f"Max channels: {sctp_transport.maxChannels}")
348
print(f"Is server: {sctp_transport.is_server}")
349
print(f"Initial state: {sctp_transport.state}")
350
351
@sctp_transport.on("statechange")
352
def on_state_change():
353
print(f"SCTP state changed to: {sctp_transport.state}")
354
```
355
356
### Complete Transport Stack
357
358
```python
359
async def complete_transport_stack():
360
"""Demonstrate the complete transport stack: ICE -> DTLS -> SCTP."""
361
362
# 1. ICE Layer - Connectivity
363
gatherer = aiortc.RTCIceGatherer()
364
365
# Configure STUN/TURN servers
366
ice_servers = [aiortc.RTCIceServer("stun:stun.l.google.com:19302")]
367
await gatherer.gather(ice_servers)
368
369
ice_transport = aiortc.RTCIceTransport(gatherer)
370
371
# 2. DTLS Layer - Security
372
dtls_transport = aiortc.RTCDtlsTransport(ice_transport)
373
374
# 3. SCTP Layer - Data delivery
375
sctp_transport = aiortc.RTCSctpTransport(dtls_transport)
376
377
# Monitor all transport states
378
@ice_transport.on("statechange")
379
def on_ice_state():
380
print(f"ICE: {ice_transport.state}")
381
382
@dtls_transport.on("statechange")
383
def on_dtls_state():
384
print(f"DTLS: {dtls_transport.state}")
385
386
@sctp_transport.on("statechange")
387
def on_sctp_state():
388
print(f"SCTP: {sctp_transport.state}")
389
390
print("Transport stack created:")
391
print(f" ICE: {ice_transport.state}")
392
print(f" DTLS: {dtls_transport.state}")
393
print(f" SCTP: {sctp_transport.state}")
394
395
return {
396
"ice": ice_transport,
397
"dtls": dtls_transport,
398
"sctp": sctp_transport
399
}
400
```
401
402
### ICE Candidate Exchange
403
404
```python
405
async def ice_candidate_exchange():
406
"""Simulate ICE candidate exchange between two peers."""
407
408
# Create two peers
409
gatherer1 = aiortc.RTCIceGatherer()
410
gatherer2 = aiortc.RTCIceGatherer()
411
412
# Gather candidates for both peers
413
await gatherer1.gather()
414
await gatherer2.gather()
415
416
# Create ICE transports
417
ice1 = aiortc.RTCIceTransport(gatherer1)
418
ice2 = aiortc.RTCIceTransport(gatherer2)
419
420
# Exchange parameters
421
params1 = gatherer1.getLocalParameters()
422
params2 = gatherer2.getLocalParameters()
423
424
print(f"Peer 1 ICE params: {params1.usernameFragment}")
425
print(f"Peer 2 ICE params: {params2.usernameFragment}")
426
427
# Exchange candidates
428
candidates1 = gatherer1.getLocalCandidates()
429
candidates2 = gatherer2.getLocalCandidates()
430
431
print(f"Peer 1 has {len(candidates1)} candidates")
432
print(f"Peer 2 has {len(candidates2)} candidates")
433
434
# Add remote candidates
435
for candidate in candidates1:
436
ice2.addRemoteCandidate(candidate)
437
438
for candidate in candidates2:
439
ice1.addRemoteCandidate(candidate)
440
441
# Start connectivity checks
442
await ice1.start(params2)
443
await ice2.start(params1)
444
445
print("ICE connectivity checks started")
446
```
447
448
### Transport Error Handling
449
450
```python
451
async def transport_error_handling():
452
"""Demonstrate transport error handling."""
453
454
try:
455
# Create transport stack
456
gatherer = aiortc.RTCIceGatherer()
457
ice_transport = aiortc.RTCIceTransport(gatherer)
458
dtls_transport = aiortc.RTCDtlsTransport(ice_transport)
459
460
# Set up error handlers
461
@ice_transport.on("error")
462
def on_ice_error(error):
463
print(f"ICE error: {error}")
464
465
@dtls_transport.on("error")
466
def on_dtls_error(error):
467
print(f"DTLS error: {error}")
468
469
# Attempt to start without proper setup (will cause errors)
470
invalid_params = aiortc.RTCIceParameters()
471
await ice_transport.start(invalid_params)
472
473
except Exception as e:
474
print(f"Transport setup failed: {e}")
475
476
finally:
477
# Clean up transports
478
if 'dtls_transport' in locals():
479
await dtls_transport.stop()
480
if 'ice_transport' in locals():
481
await ice_transport.stop()
482
483
print("Transports cleaned up")
484
```
485
486
### Transport State Monitoring
487
488
```python
489
async def monitor_transport_states():
490
"""Monitor transport state transitions."""
491
492
# Create transports
493
gatherer = aiortc.RTCIceGatherer()
494
await gatherer.gather()
495
496
ice_transport = aiortc.RTCIceTransport(gatherer)
497
dtls_transport = aiortc.RTCDtlsTransport(ice_transport)
498
sctp_transport = aiortc.RTCSctpTransport(dtls_transport)
499
500
# State tracking
501
states = {
502
"ice": ice_transport.state,
503
"dtls": dtls_transport.state,
504
"sctp": sctp_transport.state
505
}
506
507
def print_states():
508
print(f"States - ICE: {states['ice']}, DTLS: {states['dtls']}, SCTP: {states['sctp']}")
509
510
# Set up state change handlers
511
@ice_transport.on("statechange")
512
def on_ice_change():
513
states["ice"] = ice_transport.state
514
print_states()
515
516
@dtls_transport.on("statechange")
517
def on_dtls_change():
518
states["dtls"] = dtls_transport.state
519
print_states()
520
521
@sctp_transport.on("statechange")
522
def on_sctp_change():
523
states["sctp"] = sctp_transport.state
524
print_states()
525
526
print("Initial states:")
527
print_states()
528
529
# Monitor for state changes
530
await asyncio.sleep(10)
531
532
print("Final states:")
533
print_states()
534
```