RossBille
RossBille

Reputation: 1489

Difference between RTCPeerConnection.createDataChannel() and RTCPeerConnection.onDataChannel()

I have been playing around with webRTC lately and am creating an abstraction layer to easily get multiple client communication via a mesh network architecture.

The question I have is in regards to creating the data channel. At the moment i do the following:

var pc = new RTCPeerConnection(null, {optional: []});

var conn = pc.createDataChannel("testchannel", {});
var conn2 = null;
conn.onmessage = function(evt){
    console.log("onmessage1");
};

pc.ondatachannel = function (event) {
    conn2 = event.channel;
    event.channel.onmessage = function(evt){
        console.log("onmessage2");
    };
};

Which results in what seems like 2 full-duplex channels being opened up between the 2 clients. i.e. calling conn.send("message") will result in onmessage1 but calling conn2.send("message") will result in onmessage2. Is this the normal behaviour or is there something wrong with my setup?

For a bit of extra information I am testing using Chrome42 with adapter.js

Upvotes: 1

Views: 2382

Answers (2)

Dr. Alex Gouaillard
Dr. Alex Gouaillard

Reputation: 2128

  • create datachannel is active while on datachannel is passive.
  • the caller would call createdatachannel which would return a rtcdatachannel object that can be later used to send object and other things using it s own events (onmessage/onopen/onclose).
  • the callee would make sure to attach a function to the corresponding peerconnection's ondatachannel event which would extract the rtcdatachannel object from the event ( mychannel = event.channel ).

Upvotes: 1

deceze
deceze

Reputation: 522135

A data channel is indeed bi-directional; you only need to create one data channel for two peers to communicate over. Just as the initial RTC connection needs* to be created by one peer sending an offer and the other responding, a data channel needs to be opened by one peer and the other can latch onto it in ondatachannel. Then both will use send and on message of that data channel to communicate.

* Note that you can create "negotiated" data channels. Each data channel has an id; you can simply manually assign an id to your data channel. If both peers open a data channel with the same id, they do not need to "negotiate" it and can simply assume the other end is listening to the same channel. In practice I have found this to be flaky though.

Upvotes: 4

Related Questions