Skip to main content
The data-channels example demonstrates how to establish a WebRTC connection and exchange arbitrary data between a web browser and a Pion WebRTC server using DataChannels. This is the foundation for building chat applications, game state synchronization, file transfers, and more.

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

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
Choose the appropriate state based on your reconnection strategy.
This example disables Trickle ICE for simplicity:
In production, use Trickle ICE to allow ICE gathering and connection establishment to happen concurrently:
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 example
3

Complete handshake

  1. Click to generate an offer in the browser
  2. Copy the offer and paste it into the terminal
  3. Copy the answer from the terminal
  4. 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
DataChannels support both text and binary data. Use SendText() for strings and Send() for binary data ([]byte).

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