Overview
DataChannels provide a bidirectional peer-to-peer communication channel that can send arbitrary data. Unlike media tracks which are optimized for real-time audio/video, DataChannels are flexible and can be configured for different reliability and ordering requirements.Key Features
- Automatic DataChannel handling from browser
- Bidirectional message exchange
- Random message generation every 5 seconds
- Connection state monitoring
- Base64 session description encoding for easy copy-paste signaling
How It Works
1
Create PeerConnection
Initialize a new RTCPeerConnection with STUN server configuration:
2
Register DataChannel Handler
Set up a handler that fires when the browser creates a DataChannel:
3
Exchange Session Descriptions
Perform WebRTC handshake by exchanging offer and answer:
4
Send Messages
Once the channel is open, send periodic messages:
Complete Source Code
Important Concepts
Connection State vs ICE Connection State
Connection State vs ICE Connection State
The example monitors
PeerConnectionState rather than ICEConnectionState:- PeerConnectionStateFailed: No network activity for 30 seconds or another failure occurred
- PeerConnectionStateDisconnected: Faster timeout detection, but connection may recover
- PeerConnectionStateClosed: Explicit closure, usually from DTLS CloseNotify
Trickle ICE
Trickle ICE
This example disables Trickle ICE for simplicity:In production, use Trickle ICE to allow ICE gathering and connection establishment to happen concurrently:
DataChannel Reliability
DataChannel Reliability
By default, DataChannels are reliable and ordered (like TCP). You can configure them differently:This is useful for real-time gaming or other latency-sensitive applications.
Running the Example
1
Start the application
2
Open in browser
Navigate to the examples server at
http://localhost and select the Data Channels example3
Complete handshake
- Click to generate an offer in the browser
- Copy the offer and paste it into the terminal
- Copy the answer from the terminal
- Paste the answer back into the browser
4
Exchange messages
- The server will send random messages every 5 seconds
- Type messages in the browser to send them to the server
- Watch both the browser console and terminal for messages
Use Cases
Chat Applications
Build real-time messaging with low latency using DataChannels
File Transfer
Send files peer-to-peer without going through a server
Game State Sync
Synchronize game state between players in real-time
Remote Control
Send control commands to IoT devices or remote applications
Related Examples
- Data Channels Detach - Use the lower-level DataChannel API
- ORTC - Low-level ORTC API for DataChannels
- Pion to Pion - Two Pion instances communicating directly