RTCPeerConnection
Signature
const pc = new RTCPeerConnection(configuration);
// configuration: { iceServers: [{ urls: 'stun:stun.l.google.com:19302' }] }
What it does
Represents a connection between the local browser and a remote peer. It negotiates session descriptions, gathers and applies ICE candidates, and carries media tracks and data channels once a route is established.
Key members
| Member | Kind | Purpose |
|---|---|---|
createOffer() / createAnswer() |
method | Produce an SDP description to start or respond to negotiation. |
setLocalDescription() / setRemoteDescription() |
method | Apply the local or remote SDP. |
addIceCandidate() |
method | Add a candidate received from the remote peer. |
addTrack() / removeTrack() |
method | Attach or detach a media track. |
createDataChannel() |
method | Open an RTCDataChannel over the connection. |
connectionState |
property | Aggregate state: new, connecting, connected, disconnected, failed, closed. |
icecandidate |
event | Fires for each gathered local candidate; a null candidate marks the end. |
track |
event | Fires when a remote track is added. |
datachannel |
event | Fires when the remote peer opens a channel. |
Behaviour & constraints
- Negotiation is asymmetric: the offerer calls
createOffer, the answerer callscreateAnswer. - ICE candidates may arrive before or after the remote description; buffer early candidates if needed.
iceServersis optional but STUN is required to discover a public address behind NAT.- Setting a local description starts ICE gathering;
icecandidateevents follow. - Closing with
close()is final: a new connection needs a new object.
Example
const pc = new RTCPeerConnection({
iceServers: [{ urls: 'stun:stun.l.google.com:19302' }],
});
pc.onicecandidate = ({ candidate }) => {
if (candidate) signalingSend({ candidate });
};
const offer = await pc.createOffer();
await pc.setLocalDescription(offer);
signalingSend({ sdp: pc.localDescription });