Data Channels
Core API
This page uses the core API in dev.onvoid.webrtc, which leaves negotiation, threads and cleanup to you. For the client API, see Data Channels.
This guide explains how to use WebRTC data channels with the webrtc-java library. Data channels provide a bidirectional communication mechanism that can be used to send arbitrary data between peers.
Overview
WebRTC data channels allow you to:
- Send and receive text or binary data between peers
- Configure reliability and ordering properties
- Set up multiple channels with different configurations
- Monitor channel state changes and buffer amounts
Data channels are created through an RTCPeerConnection and use the SCTP protocol for data transmission.
Creating a Data Channel
To create a data channel, you need an established RTCPeerConnection. You can then call the createDataChannel method with a label and optional configuration:
import dev.onvoid.webrtc.RTCPeerConnection;
import dev.onvoid.webrtc.RTCDataChannel;
import dev.onvoid.webrtc.RTCDataChannelInit;
// Assuming you already have a PeerConnectionFactory and RTCConfiguration
RTCPeerConnection peerConnection = factory.createPeerConnection(config, peerConnectionObserver);
// Create a data channel with default configuration
RTCDataChannel dataChannel = peerConnection.createDataChannel("myChannel", new RTCDataChannelInit());Data Channel Configuration
You can customize the behavior of a data channel by configuring the RTCDataChannelInit object:
RTCDataChannelInit config = new RTCDataChannelInit();
// Configure ordering (default: true)
config.ordered = true; // Messages will be delivered in order
// Configure reliability
// Option 1: Reliable (default)
config.maxPacketLifeTime = -1;
config.maxRetransmits = -1;
// Option 2: Time-limited reliability
config.maxPacketLifeTime = 1000; // Retransmit for up to 1000ms
config.maxRetransmits = -1; // Don't use retransmit count limit
// Option 3: Count-limited reliability
config.maxPacketLifeTime = -1; // Don't use time limit
config.maxRetransmits = 5; // Retransmit up to 5 times
// Note: You cannot set both maxPacketLifeTime and maxRetransmits
// Configure channel negotiation (default: false)
config.negotiated = false; // Channel will be announced in-band
// Configure channel ID (default: -1, auto-assigned)
config.id = -1; // Let WebRTC assign an ID
// Configure sub-protocol (default: null)
config.protocol = "my-protocol"; // Optional sub-protocol name
// Configure priority (default: LOW), announced to the remote peer
config.priority = RTCPriorityType.HIGH;
// Create the data channel with this configuration
RTCDataChannel dataChannel = peerConnection.createDataChannel("myChannel", config);getPriority() returns a channel's priority; a channel the remote peer opened has the priority it announced. WebRTC only uses the priority to share the connection between channels when SCTP message interleaving is on, which needs the field trial WebRTC-DataChannelMessageInterleaving/Enabled/ on both peers (see Field Trials). Without it, channels take turns regardless of priority.
Handling Data Channel Events
To receive events from a data channel, you need to implement the RTCDataChannelObserver interface and register it with the data channel:
import dev.onvoid.webrtc.RTCDataChannelObserver;
import dev.onvoid.webrtc.RTCDataChannelBuffer;
import dev.onvoid.webrtc.RTCDataChannelState;
dataChannel.registerObserver(new RTCDataChannelObserver() {
@Override
public void onBufferedAmountChange(long sentDataSize) {
// The callback reports a decrease, not the previous queue size.
long currentAmount = dataChannel.getBufferedAmount();
System.out.println("Buffered amount decreased by " + sentDataSize +
" to " + currentAmount + " bytes");
}
@Override
public void onStateChange() {
// Called when the data channel state changes
RTCDataChannelState state = dataChannel.getState();
System.out.println("Data channel state changed to: " + state);
// Handle different states
switch (state) {
case CONNECTING:
System.out.println("Data channel is being established");
break;
case OPEN:
System.out.println("Data channel is open and ready to use");
break;
case CLOSING:
System.out.println("Data channel is being closed");
break;
case CLOSED:
System.out.println("Data channel is closed");
break;
}
}
@Override
public void onMessage(RTCDataChannelBuffer buffer) {
// Called when a message is received
// IMPORTANT: The buffer data will be freed after this method returns,
// so you must copy it if you need to use it asynchronously
if (buffer.binary) {
// Handle binary data
handleBinaryMessage(buffer.data);
} else {
// Handle text data
handleTextMessage(buffer.data);
}
}
});Receiving Data Channels
When the remote peer creates a data channel, the onDataChannel method of your PeerConnectionObserver will be called:
import dev.onvoid.webrtc.PeerConnectionObserver;
public class MyPeerConnectionObserver implements PeerConnectionObserver {
// Other PeerConnectionObserver methods...
@Override
public void onDataChannel(RTCDataChannel dataChannel) {
System.out.println("Received data channel: " + dataChannel.getLabel());
// Register an observer to handle events from this channel
dataChannel.registerObserver(new MyDataChannelObserver());
}
}Sending and Receiving Data
Sending Data
You can send text or binary data through a data channel using the send method:
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
// Send text data
String textMessage = "Hello, WebRTC!";
ByteBuffer textBuffer = ByteBuffer.wrap(textMessage.getBytes(StandardCharsets.UTF_8));
RTCDataChannelBuffer textChannelBuffer = new RTCDataChannelBuffer(textBuffer, false);
try {
dataChannel.send(textChannelBuffer);
} catch (Exception e) {
System.err.println("Failed to send text message: " + e.getMessage());
}
// Send binary data
byte[] binaryData = new byte[] { 0x01, 0x02, 0x03, 0x04 };
ByteBuffer binaryBuffer = ByteBuffer.wrap(binaryData);
RTCDataChannelBuffer binaryChannelBuffer = new RTCDataChannelBuffer(binaryBuffer, true);
try {
dataChannel.send(binaryChannelBuffer);
} catch (Exception e) {
System.err.println("Failed to send binary data: " + e.getMessage());
}Sending Data Asynchronously
send queues the message on the calling thread. sendAsync hands the message to the native network thread instead and returns immediately, which suits senders that must not block. The readable window of the buffer is copied before the method returns, so the buffer can be reused right away.
To learn whether the native send operation accepted the message, pass an RTCDataChannelSendObserver:
dataChannel.sendAsync(binaryChannelBuffer, new RTCDataChannelSendObserver() {
@Override
public void onSuccess() {
// The local send operation accepted the message.
}
@Override
public void onFailure(String error) {
// For example "[INVALID_STATE] ..." when the channel is not open.
System.err.println("Send failed: " + error);
}
});The observer is called exactly once, with a failure if the operation is discarded while the channel shuts down. Success means the message was queued locally, not that the peer received it.
Callbacks run on a native callback thread shared with other WebRTC observers. They may call other WebRTC methods, but should not block, so dispatch long work to an executor of your own. Without an observer, sendAsync logs failures and reports nothing to the caller.
Sending More When the Buffer Drains
A sender of a large amount of data should not queue all of it at once. It keeps the buffer between two marks instead: it pauses above a high mark of its own, and resumes once the buffered amount falls to a low threshold. setBufferedAmountLowThreshold sets that threshold, and onBufferedAmountLow tells the observer when the buffered amount falls to it:
long highMark = 1024 * 1024;
dataChannel.setBufferedAmountLowThreshold(256 * 1024);
dataChannel.registerObserver(new RTCDataChannelObserver() {
@Override
public void onBufferedAmountLow() {
// Room again: send until the high mark is reached.
executor.execute(() -> sendWhileBelow(highMark));
}
// onBufferedAmountChange, onStateChange and onMessage as above.
});The event comes once each time the buffered amount falls from above the threshold to the threshold or below. The threshold is 0 until set, so by default the event tells when the buffer is empty.
WebRTC reports the buffered amount in steps of about 100 KiB, not for every message. The event may therefore come only once the amount has fallen somewhat below the threshold. A message sent with sendAsync before the channel is open is refused and not counted.
Receiving Data
To receive data, implement the onMessage method in your RTCDataChannelObserver:
@Override
public void onMessage(RTCDataChannelBuffer buffer) {
ByteBuffer data = buffer.data;
if (buffer.binary) {
// Handle binary data
byte[] binaryData;
if (data.hasArray()) {
binaryData = data.array();
} else {
binaryData = new byte[data.remaining()];
data.get(binaryData);
}
System.out.println("Received binary data, " + binaryData.length + " bytes");
// Process binary data...
} else {
// Handle text data
byte[] textBytes;
if (data.hasArray()) {
textBytes = data.array();
} else {
textBytes = new byte[data.remaining()];
data.get(textBytes);
}
String text = new String(textBytes, StandardCharsets.UTF_8);
System.out.println("Received text message: " + text);
// Process text message...
}
}Data Channel Properties
You can query various properties of a data channel:
// Get the channel label
String label = dataChannel.getLabel();
// Check if the channel is reliable
boolean reliable = dataChannel.isReliable();
// Check if messages are delivered in order
boolean ordered = dataChannel.isOrdered();
// Get the maximum packet lifetime (in milliseconds)
int maxPacketLifeTime = dataChannel.getMaxPacketLifeTime();
// Get the maximum number of retransmits
int maxRetransmits = dataChannel.getMaxRetransmits();
// Get the sub-protocol
String protocol = dataChannel.getProtocol();
// Check if the channel was negotiated by the application
boolean negotiated = dataChannel.isNegotiated();
// Get the channel ID
int id = dataChannel.getId();
// Get the current state
RTCDataChannelState state = dataChannel.getState();
// Get the amount of buffered data (in bytes)
long bufferedAmount = dataChannel.getBufferedAmount();Message Size and Channel Limits
All data channels of a connection share one SCTP transport. It knows how large a message the remote peer accepts, and how many channels can be open at once:
RTCSctpTransport transport = peerConnection.getSctpTransport();
if (transport != null) {
Double maxMessageSize = transport.getMaxMessageSize(); // in bytes, null while unknown
Integer maxChannels = transport.getMaxChannels(); // null until connected
transport.dispose();
}Split a message larger than getMaxMessageSize() into parts, since the channel refuses it. Two WebRTC peers agree on 256 KiB. getSctpTransport() returns null until a description with data channels is applied. Each call returns a new RTCSctpTransport, which you dispose. getState() tells whether the association is CONNECTING, CONNECTED or CLOSED, and getTransport() returns the DTLS transport beneath it.
Closing and Cleanup
When you're done with a data channel, you should properly clean it up:
// Unregister the observer
dataChannel.unregisterObserver();
// Close the data channel
dataChannel.close();
// Dispose of native resources
dataChannel.dispose();Unlike other disposable objects, a data channel is not disposed by close(), which only closes the channel. A try-with-resources statement therefore does not release it: call dispose() yourself.
Best Practices
Error Handling: Always wrap
sendcalls in try-catch blocks as they can throw exceptions if the buffer is full or the channel is not in theOPENstate.Buffer Management: Monitor the buffered amount to avoid overwhelming the channel. If
getBufferedAmount()returns a large value, pause sending untilonBufferedAmountLowtells you it has room again.Copy Received Data: Remember that the data in the
RTCDataChannelBufferwill be freed after theonMessagemethod returns. If you need to process the data asynchronously, make a copy of it.Proper Cleanup: Always unregister observers, close channels, and dispose of native resources to prevent memory leaks.
State Checking: Check the channel state before sending data to avoid exceptions:
javaif (dataChannel.getState() == RTCDataChannelState.OPEN) { // Safe to send data }Multiple Channels: Consider using multiple data channels with different configurations for different types of data (e.g., one reliable channel for critical data and one unreliable channel for real-time updates).
Binary vs. Text: Use the appropriate flag when creating
RTCDataChannelBufferobjects:falsefor UTF-8 text datatruefor binary data
