This example demonstrates local peer-to-peer communication. Both agents run on the same machine, but the same principles apply to remote connections.
Overview
Establishing an ICE connection involves:- Creating ICE agents on both sides
- Gathering local candidates (network addresses)
- Exchanging credentials and candidates with the remote peer
- Performing connectivity checks
- Using the established connection to send/receive data
Complete Example
Here’s a full working example that establishes an ICE connection between two peers:Set up event handlers
Register handlers for candidates and connection state changes:
OnCandidate is called with nil when candidate gathering completes.Exchange ICE credentials
Get local credentials and share them with the remote peer:The username fragment (ufrag) and password (pwd) are used to authenticate connectivity checks.
Gather candidates
Start gathering network candidates:This discovers all available network paths (local addresses, STUN reflexive addresses, TURN relay addresses).
Full Working Example
Here’s a complete ping-pong example that demonstrates the entire flow. This example uses HTTP for signaling (exchanging credentials and candidates):Key Concepts Explained
ICE Candidates
Candidates represent possible network paths:- Host candidates: Your local IP addresses and ports
- Server reflexive candidates: Your public IP (discovered via STUN)
- Relay candidates: TURN server addresses (for difficult NAT scenarios)
Controlling vs Controlled
ICE requires one peer to be “controlling” (initiates nomination) and the other “controlled” (responds). This is separate from client/server - either peer can be controlling.Connection States
Watch for these states during connection:Adding STUN/TURN Servers
For connections across the internet, add STUN/TURN servers:Continual Gathering
For applications that need to adapt to network changes (like mobile apps), enable continual gathering:Next Steps
Agent Configuration
Learn about all available agent options
Candidate Types
Deep dive into ICE candidates
NAT Traversal
Configure STUN and TURN servers
Examples
Explore more code examples