1

I am a newbie to WebRTC. I am building an application that enables users to view each other's video stream, as well as exchange files. The audio/video part is implemented and working. The problem is I need to add the ability to exchange files now. I am using the below code to initialize the PeerConnection object

var connection = _getConnection(partnerId);
console.log("Initiate offer")
// Add our audio/video stream
connection.addStream(stream);

// Send an offer for a connection
connection.createOffer(function (desc) { _createOfferSuccess(connection, partnerId, desc) }, function (error) { console.log('Error creating session description: ' + error); });

_getConnection creates a new RTCPeerConnection object using

var connection = new RTCPeerConnection(iceconfig); 

i.e., with no explicit constraints. It also initializes the different event handlers on it. Right after this, I attach the audio/video stream to this connection. I also cache these connections using the partner id, so I can use it later.

The question is, can I later recall the connection object from the cache, add a data channel to it using something like

connection.createDataChannel("DataChannel", dataChannelOptions);

And use it to share files, or do I have to create a new RTCPeerConnection object and attach the data channel to it?

DrHSF
  • 11
  • 1
  • 2
  • 1
    I've not been able to create a datachannel if it was initialized as audio/video, and vice versa. The implementation seems to be one or the other. – koush Jul 13 '16 at 19:20

1 Answers1

0

You certainly do not have to create a another PeerConnection for file transfer alone. Existing PeerConnection can utilize RTCDatachannel with behaves like traditional websocket mechanism ( ie 2 way communication without a central server )

`var PC = new RTCPeerConnection();

//specifying options for my datachannel 
var dataChannelOptions = {
  ordered: false, // unguaranted sequence
  maxRetransmitTime: 2000, // 2000 miliseconds is the maximum time to try and retrsanmit failed messages 
  maxRetransmits : 5  // 5 is the number of times to try to retransmit failed messages , other options are negotiated , id , protocol   
};


// createing data channel using RTC datachannel API name DC1
var dataChannel = PC.createDataChannel("DC1", dataChannelOptions);

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

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

dataChannel.onopen = function () {
  dataChannel.send(" Sending 123 ");  // you can add file here in either strings/blob/array bufers almost anyways
};

dataChannel.onclose = function () {
  console.log("DC is Closed");
};

 `

PS : while sending files over datachannel API , it is advisable to break down the files into small chunks beforehand . I suggest chunk size of almost 10 - 15 KB .

Altanai
  • 1,323
  • 1
  • 19
  • 33