如何在WebRTC对等连接中创建数据通道?

2023-12-21

我正在尝试学习如何创建一个RTCPeerConnection这样我就可以使用DataChannelAPI。这是我根据我的理解尝试过的:

var client = new mozRTCPeerConnection;
var server = new mozRTCPeerConnection;

client.createOffer(function (description) {
    client.setLocalDescription(description);
    server.setRemoteDescription(description);

    server.createAnswer(function (description) {
        server.setLocalDescription(description);
        client.setRemoteDescription(description);

        var clientChannel = client.createDataChannel("chat");
        var serverChannel = server.createDataChannel("chat");

        clientChannel.onmessage = serverChannel.onmessage = onmessage;

        clientChannel.send("Hello Server!");
        serverChannel.send("Hello Client!");

        function onmessage(event) {
            alert(event.data);
        }
    });
});

我不确定出了什么问题,但我假设连接从未建立,因为没有显示消息。

我在哪里可以了解更多相关信息?我已经读过WebRTC 入门 - HTML5 Rocks http://www.html5rocks.com/en/tutorials/webrtc/basics/教程。


翻阅了很多文章,终于搞定了:http://jsfiddle.net/LcQzV/ http://jsfiddle.net/LcQzV/

首先我们创建对等连接:

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

当客户端连接到服务器时,它必须打开一个数据通道:

client.onconnection = function () {
    var channel = client.createDataChannel("chat", {});

    channel.onmessage = function (event) {
        alert("Server: " + event.data);
    };

    channel.onopen = function () {
        channel.send("Hello Server!");
    };
};

当客户端创建数据通道时,服务器可能会响应:

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

    channel.onopen = function () {
        channel.send("Hello Client!");
    };
};

我们需要向客户端和服务器添加一个假音频流来建立连接:

navigator.mozGetUserMedia(media, callback, errback);

function callback(fakeAudio) {
    server.addStream(fakeAudio);
    client.addStream(fakeAudio);
    client.createOffer(offer);
}

function errback(error) {
    alert(error);
}

客户创建报价:

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

服务器接受报价并建立连接:

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);
        });
    });
}

唷。这花了一段时间才明白。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在WebRTC对等连接中创建数据通道? 的相关文章

随机推荐