Skip to main content

Overview

The PeerConnection is the central component in Pion WebRTC, representing a connection between two peers. It manages the entire lifecycle of a WebRTC session, from ICE candidate gathering to media transmission.
peerconnection.go

Creating a PeerConnection

Using Default Settings

Using Custom API

The source code shows how NewPeerConnection works:
peerconnection.go
Each PeerConnection gets a unique ID based on the current timestamp, useful for debugging and logging.

Signaling States

The PeerConnection goes through different signaling states during negotiation:
1

Stable

No offer/answer exchange in progress. This is the initial state and the state after a successful negotiation.
2

Have Local Offer

Local peer has created an offer and called SetLocalDescription().
3

Have Remote Offer

Remote peer has sent an offer which was set via SetRemoteDescription().
4

Have Local Pranswer

Local peer has created a provisional answer.
5

Have Remote Pranswer

Remote peer has sent a provisional answer.

Monitoring Signaling State

peerconnection.go
The implementation from the source:
peerconnection.go

Connection States

The overall connection state is derived from ICE and DTLS transport states:
peerconnection.go

Connection State Handlers

Creating Offers and Answers

Creating an Offer

peerconnection.go
Example usage:
You can trigger an ICE restart by passing &webrtc.OfferOptions{ICERestart: true} to CreateOffer().

Creating an Answer

peerconnection.go
Example usage:

Setting Descriptions

Setting Local Description

peerconnection.go

Setting Remote Description

peerconnection.go
Always set the remote description before creating an answer. Attempting to create an answer without a remote offer will result in an error.

Adding Tracks

Receiving Tracks

peerconnection.go
From the source code:
peerconnection.go

Negotiation Needed

Pion automatically detects when renegotiation is needed:
peerconnection.go
Handle renegotiation:

Configuration Updates

peerconnection.go
Most configuration fields cannot be changed after the PeerConnection is created. Only ICE servers can be safely updated.

Closing Connections

Always close PeerConnections to free resources:

Next Steps

Signaling

Learn about SDP exchange and signaling protocols

ICE & Connectivity

Deep dive into ICE candidates and NAT traversal