How to create data channel in WebRTC peer connection?

后端 未结 3 620
你的背包
你的背包 2021-01-31 06:24

I\'m trying to learn how to create an RTCPeerConnection so that I can use the DataChannel API. Here\'s what I have tried from what I understood:

<
3条回答
  •  难免孤独
    2021-01-31 06:51

    I finally got it to work after sifting through a lot of articles: http://jsfiddle.net/LcQzV/

    First we create the peer connections:

    var media = {};
    media.fake = media.audio = true;
    var client = new mozRTCPeerConnection;
    var server = new mozRTCPeerConnection;
    

    When the client connects to the server it must open a data channel:

    client.onconnection = function () {
        var channel = client.createDataChannel("chat", {});
    
        channel.onmessage = function (event) {
            alert("Server: " + event.data);
        };
    
        channel.onopen = function () {
            channel.send("Hello Server!");
        };
    };
    

    When the client creates a data channel the server may respond:

    server.ondatachannel = function (channel) {
        channel.onmessage = function (event) {
            alert("Client: " + event.data);
        };
    
        channel.onopen = function () {
            channel.send("Hello Client!");
        };
    };
    

    We need to add a fake audio stream to the client and the server to establish a connection:

    navigator.mozGetUserMedia(media, callback, errback);
    
    function callback(fakeAudio) {
        server.addStream(fakeAudio);
        client.addStream(fakeAudio);
        client.createOffer(offer);
    }
    
    function errback(error) {
        alert(error);
    }
    

    The client creates an offer:

    function offer(description) {
        client.setLocalDescription(description, function () {
            server.setRemoteDescription(description, function () {
                server.createAnswer(answer);
            });
        });
    }
    

    The server accepts the offer and establishes a connection:

    function answer(description) {
        server.setLocalDescription(description, function () {
            client.setRemoteDescription(description, function () {
                var port1 = Date.now();
                var port2 = port1 + 1;
    
                client.connectDataConnection(port1, port2);
                server.connectDataConnection(port2, port1);
            });
        });
    }
    

    Phew. That took a while to understand.

提交回复
热议问题