Skip to content

WebRTC DataChannel and Firefox

muaz-khan edited this page Apr 3, 2013 · 1 revision

Copy/paste below code in the console section of Firefox/Firebug:

function setChannelEvents(channel, channelNameForConsoleOutput) {
    console.debug('protocol of', channelNameForConsoleOutput, 'is', channel.protocol);
    channel.onmessage = function (event) {
        console.debug(channelNameForConsoleOutput, 'received a message:', event.data);
    };
    channel.onopen = function () {
        channel.send('first text message over SCTP data ports');
    };
    channel.onclose = function (e) {
        console.error(e);
    };
    channel.onerror = function (e) {
        console.error(e);
    };
}

function useless() {}

var iceServers = {
    iceServers: [{
            url: 'stun:23.21.150.121'
        }
    ]
};

var offerer = new mozRTCPeerConnection(iceServers),
    answerer, answererDataChannel, offererDataChannel;

offererDataChannel = offerer.createDataChannel('channel', {});
offererDataChannel.binaryType = 'blob';
setChannelEvents(offererDataChannel, 'offerer');

navigator.mozGetUserMedia({
    audio: true,
    fake: true
}, function (stream) {
    offerer.addStream(stream);

    offerer.createOffer(function (sessionDescription) {
        offerer.setLocalDescription(sessionDescription);
        createAnswer(sessionDescription);
    }, null, mediaConstraints);

}, useless);

var mediaConstraints = {
    optional: [],
    mandatory: {
        OfferToReceiveAudio: true,
        OfferToReceiveVideo: true
    }
};

function createAnswer(offerSDP) {
    answerer = new mozRTCPeerConnection(iceServers);
    answerer.ondatachannel = function (event) {
        answererDataChannel = event.channel;
        answererDataChannel.binaryType = 'blob';
        setChannelEvents(answererDataChannel, 'answerer');
    };

    navigator.mozGetUserMedia({
        audio: true,
        fake: true
    }, function (stream) {

        answerer.addStream(stream);
        answerer.setRemoteDescription(offerSDP);

        answerer.createAnswer(function (sessionDescription) {
            answerer.setLocalDescription(sessionDescription);

            offerer.setRemoteDescription(sessionDescription);
        }, null, mediaConstraints);

    }, useless);
}

Send a text message from offerer's side

offererDataChannel.send('----text message ----');

Send a text message from answerer's side

answererDataChannel.send('----text message ----');

Points

  1. createDataChannel method must be called before calling createOffer:

       peerConnection.createDataChannel('channel', {});
       peerConnection.createOffer(offerSDP, onsuccess);
  2. connectDataConnection is deprecated.

  3. ondatachannel now takes an event instead of a raw channel.

       peerConnection.ondatachannel(function(event) {
             var channel = event.channel;
       });

See this page for further details about new changes in DataChannel implementation on Firefox.