Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending JSON data over WebRTC

I am new to WebRTC native framework.

I was able to get the WebRTC source and run the demo Android application based on http://andrii.sergiienko.me/?go=all/building-webrtc-demo-for-android/enter link description here.

I was able to send/receive Audio and Video between two Android devices on the same local network.

Is there any way to send a small JSON payload in this peer connection?

I tried looking for it in the source and I only found support to send Video and Audio.

Thank you.

like image 201
Anil Maddala Avatar asked Oct 17 '25 03:10

Anil Maddala


1 Answers

Your are looking for WebRTC DataChannels.

WebRTC's RTCDataChannel API is used to transfer data directly from one peer to another. This is great for sending data between two browsers(Peers) for activities like communication, gaming, or file transfer and slew of other functionalities.

It is an Alternative For WebSockets:

This is a great alternative to WebSockets because no central server is involved and transmission is usually faster and there is no bottleneck. You can of course mitigate the failover of P2P transfer by having a hooks which activates Websockets based communication if P2P data-channel communication fails.

Code for Reference:

The events defined are called when you wish to send a message of when a message is received (including error handling). This code should be running in both the browsers. Instead of sending "Hello World" you just need to send your JSON String.

var peerConnection = new RTCPeerConnection();

// Establish your peer connection using your signaling channel here
var dataChannel =
  peerConnection.createDataChannel("myLabel", dataChannelOptions);

dataChannel.onerror = function (error) {
  console.log("Data Channel Error:", error);
};

dataChannel.onmessage = function (event) {
  console.log("Got Data Channel Message:", event.data);
};

dataChannel.onopen = function () {
  dataChannel.send("Hello World!");
};

dataChannel.onclose = function () {
  console.log("The Data Channel is Closed");
};

The dataChannel object is created from an already established peer connection. It can be created before or after signaling happens. You then pass in a label to distinguish this channel from others and a set of optional configuration settings:

var dataChannelOptions = {
  ordered: false, // do not guarantee order
  maxRetransmitTime: 3000, // in milliseconds
};

For more details check out the links provided.

Examples:

Link to official documentation: DataChannels in WebRTC

Link to a file Trasfer example using WebRTC Data Channels. File Transfer

Link to popular Use Cases for WebRTC Data Channels Use Cases

like image 88
Maneshwar Singh Avatar answered Oct 19 '25 22:10

Maneshwar Singh