0
# Peer Connection Management
1
2
Core WebRTC peer connection functionality providing the main entry point for establishing and managing real-time communication sessions between peers.
3
4
## Capabilities
5
6
### RTCPeerConnection Class
7
8
The main class for managing WebRTC peer connections, handling signaling, ICE candidates, media tracks, and data channels.
9
10
```python { .api }
11
class RTCPeerConnection:
12
def __init__(self, configuration=None):
13
"""
14
Create a new RTCPeerConnection.
15
16
Parameters:
17
- configuration (RTCConfiguration, optional): Connection configuration
18
"""
19
20
# Properties
21
@property
22
def connectionState(self) -> str:
23
"""Current connection state: "new", "connecting", "connected", "disconnected", "failed", "closed" """
24
25
@property
26
def iceConnectionState(self) -> str:
27
"""ICE connection state: "new", "checking", "connected", "completed", "failed", "disconnected", "closed" """
28
29
@property
30
def iceGatheringState(self) -> str:
31
"""ICE gathering state: "new", "gathering", "complete" """
32
33
@property
34
def localDescription(self) -> RTCSessionDescription:
35
"""Local session description"""
36
37
@property
38
def remoteDescription(self) -> RTCSessionDescription:
39
"""Remote session description"""
40
41
@property
42
def signalingState(self) -> str:
43
"""Signaling state: "stable", "have-local-offer", "have-remote-offer", "have-local-pranswer", "have-remote-pranswer", "closed" """
44
45
@property
46
def sctp(self) -> Optional[RTCSctpTransport]:
47
"""SCTP transport for data channels, or None if not available"""
48
49
# Session Description Methods
50
async def createOffer(self) -> RTCSessionDescription:
51
"""
52
Create an offer session description.
53
54
Returns:
55
RTCSessionDescription: SDP offer
56
"""
57
58
async def createAnswer(self) -> RTCSessionDescription:
59
"""
60
Create an answer session description.
61
62
Returns:
63
RTCSessionDescription: SDP answer
64
"""
65
66
async def setLocalDescription(self, description: RTCSessionDescription) -> None:
67
"""
68
Set the local session description.
69
70
Parameters:
71
- description (RTCSessionDescription): Local SDP offer or answer
72
"""
73
74
async def setRemoteDescription(self, description: RTCSessionDescription) -> None:
75
"""
76
Set the remote session description.
77
78
Parameters:
79
- description (RTCSessionDescription): Remote SDP offer or answer
80
"""
81
82
# ICE Candidate Management
83
async def addIceCandidate(self, candidate: RTCIceCandidate) -> None:
84
"""
85
Add a remote ICE candidate.
86
87
Parameters:
88
- candidate (RTCIceCandidate): Remote ICE candidate
89
"""
90
91
# Media Track Management
92
def addTrack(self, track: MediaStreamTrack, *streams) -> RTCRtpSender:
93
"""
94
Add a media track to the connection.
95
96
Parameters:
97
- track (MediaStreamTrack): Audio or video track to add
98
- streams: Associated media streams (unused in current implementation)
99
100
Returns:
101
RTCRtpSender: RTP sender for the track
102
"""
103
104
def addTransceiver(self, trackOrKind, direction="sendrecv") -> RTCRtpTransceiver:
105
"""
106
Add an RTP transceiver.
107
108
Parameters:
109
- trackOrKind: MediaStreamTrack or media kind string ("audio", "video")
110
- direction (str): Transceiver direction ("sendrecv", "sendonly", "recvonly", "inactive")
111
112
Returns:
113
RTCRtpTransceiver: Created transceiver
114
"""
115
116
# Data Channel Management
117
def createDataChannel(self, label: str, **options) -> RTCDataChannel:
118
"""
119
Create a data channel.
120
121
Parameters:
122
- label (str): Channel label/name
123
- maxPacketLifeTime (int, optional): Maximum packet lifetime in milliseconds
124
- maxRetransmits (int, optional): Maximum retransmission attempts
125
- ordered (bool, optional): Whether to guarantee ordered delivery (default: True)
126
- protocol (str, optional): Subprotocol name
127
- negotiated (bool, optional): Whether channel is pre-negotiated (default: False)
128
- id (int, optional): Numeric channel identifier (0-65534)
129
130
Returns:
131
RTCDataChannel: Created data channel
132
"""
133
134
# Information Methods
135
def getReceivers(self) -> list:
136
"""
137
Get list of RTP receivers.
138
139
Returns:
140
list: List of RTCRtpReceiver objects
141
"""
142
143
def getSenders(self) -> list:
144
"""
145
Get list of RTP senders.
146
147
Returns:
148
list: List of RTCRtpSender objects
149
"""
150
151
def getTransceivers(self) -> list:
152
"""
153
Get list of RTP transceivers.
154
155
Returns:
156
list: List of RTCRtpTransceiver objects
157
"""
158
159
async def getStats(self) -> RTCStatsReport:
160
"""
161
Get connection statistics.
162
163
Returns:
164
RTCStatsReport: Statistics for all tracks and transports
165
"""
166
167
# Connection Management
168
async def close(self) -> None:
169
"""Close the peer connection and release resources."""
170
```
171
172
### Session Description Management
173
174
Handle SDP offers and answers for session negotiation.
175
176
```python { .api }
177
class RTCSessionDescription:
178
def __init__(self, sdp: str, type: str):
179
"""
180
Create a session description.
181
182
Parameters:
183
- sdp (str): Session Description Protocol string
184
- type (str): Description type ("offer", "answer", "pranswer", "rollback")
185
"""
186
187
@property
188
def sdp(self) -> str:
189
"""SDP string content"""
190
191
@property
192
def type(self) -> str:
193
"""Description type"""
194
```
195
196
### Usage Examples
197
198
#### Basic Peer Connection Setup
199
200
```python
201
import aiortc
202
import asyncio
203
204
async def setup_peer_connection():
205
# Create configuration with STUN server
206
config = aiortc.RTCConfiguration(
207
iceServers=[aiortc.RTCIceServer("stun:stun.l.google.com:19302")]
208
)
209
210
# Create peer connection
211
pc = aiortc.RTCPeerConnection(configuration=config)
212
213
# Add event listeners
214
@pc.on("connectionstatechange")
215
def on_connectionstatechange():
216
print(f"Connection state: {pc.connectionState}")
217
218
@pc.on("icecandidate")
219
def on_icecandidate(candidate):
220
# Send candidate to remote peer
221
print(f"New ICE candidate: {candidate}")
222
223
return pc
224
225
pc = asyncio.run(setup_peer_connection())
226
```
227
228
#### Offer/Answer Exchange
229
230
```python
231
async def create_offer_answer():
232
pc1 = aiortc.RTCPeerConnection()
233
pc2 = aiortc.RTCPeerConnection()
234
235
# PC1 creates offer
236
offer = await pc1.createOffer()
237
await pc1.setLocalDescription(offer)
238
239
# PC2 processes offer and creates answer
240
await pc2.setRemoteDescription(offer)
241
answer = await pc2.createAnswer()
242
await pc2.setLocalDescription(answer)
243
244
# PC1 processes answer
245
await pc1.setRemoteDescription(answer)
246
247
# Connections are now established (pending ICE)
248
print(f"PC1 signaling state: {pc1.signalingState}")
249
print(f"PC2 signaling state: {pc2.signalingState}")
250
```
251
252
#### Adding Media and Data
253
254
```python
255
async def add_media_and_data():
256
pc = aiortc.RTCPeerConnection()
257
258
# Add audio and video tracks
259
audio_track = aiortc.AudioStreamTrack()
260
video_track = aiortc.VideoStreamTrack()
261
262
pc.addTrack(audio_track)
263
pc.addTrack(video_track)
264
265
# Create data channel
266
channel = pc.createDataChannel("chat", ordered=True)
267
268
@channel.on("open")
269
def on_open():
270
print("Data channel opened")
271
channel.send("Hello WebRTC!")
272
273
@channel.on("message")
274
def on_message(message):
275
print(f"Received: {message}")
276
277
# Get connection info
278
senders = pc.getSenders()
279
receivers = pc.getReceivers()
280
transceivers = pc.getTransceivers()
281
282
print(f"Senders: {len(senders)}")
283
print(f"Receivers: {len(receivers)}")
284
print(f"Transceivers: {len(transceivers)}")
285
```
286
287
## Types
288
289
```python { .api }
290
from typing import Optional
291
from aiortc import RTCSctpTransport
292
293
# Optional type for nullable values
294
Optional[T] # Union of T and None
295
```