我正在创建一个webRTC连接,用于在两个对等点之间传输数据。目前,我正处于让channel.readyState进入“开放”状态的阶段。有人能帮助我理解为什么代码块2中的"ondatachannel()“和代码块1事件侦听器中的"onopen()”不会触发吗?当我在开发工具控制台中手动输入所有代码时,它可以工作。我使用django后端和django通道进行sdp交换。
实例化RTCPeerConnection并向后端发送本地描述。
function hostroom(){
lc = new RTCPeerConnection()
dc = lc.createDataChannel("channel")
dc.onmessage = e =>("Just got a message " + e.data);
dc.onopen = e => console.log("Connection opened!")
lc.onicecandidate = function(e){
console.log("icecandidate created");
}
lc.createOffer().then(o => lc.setLocalDescription(o)).then(a => console.log("set successfully!")).then(
function (){
var ice = JSON.stringify(lc.localDescription);
console.log(ice);
var csrftoken = $("[name=csrfmiddlewaretoken]").val();
var p={{p.id}}
$.ajax({
type: 'POST',
url: '{% url 'createroom' %}',
data:{
"ice": ice,
"csrfmiddlewaretoken": csrftoken,
"p": p,
},
success: function (data) {
alert(data["response"])
}
});
}
)开发工具控制台上的输出:

远程对等端的代码。在页面加载时运行,并将本地描述通过后端发送,然后通过django通道发送到主机。
const rc = new RTCPeerConnection();
rc.onicecandidate = function(e){
console.log("New Ice Candidate reprinting SDP " + JSON.stringify(rc.localDescription));
}
rc.ondatachannel = e => {
rc.dc = e.channel;
rc.dc.onmessage = e => console.log("new message from client! " + e.data);
rc.dc.onopen = e => console.log("Connection opened!");
};
var offer = {{icecandidate|safe}}
rc.setRemoteDescription(offer).then(a => console.log("offer set!"));
rc.createAnswer().then(a => rc.setLocalDescription(a)).then(a => console.log("local d set!")).then(
function(){
var answer = JSON.stringify(rc.localDescription)
console.log(answer)
var csrftoken = $("[name=csrfmiddlewaretoken]").val();
var user = document.getElementById("account").text.split(":")[1];
var room_name="{{room_name}}"
console.log(room_name);
$.post("{% url 'connecttoleader' %}", {
"answer": answer,
"csrfmiddlewaretoken": csrftoken,
"user": user,
"room_name": room_name,
});
}
);开发工具控制台上的输出:

回到主人身边。代码在与代码块1相同的浏览器选项卡上触发djangochannelsocket.onmessage() (上面的第一个代码块)。
...
var csrftoken = $("[name=csrfmiddlewaretoken]").val();
console.log(JSON.parse(sdp))
lc.setRemoteDescription(JSON.parse(sdp))
console.log("set")
channel = "dc"
$.ajax({
type: 'POST',
url: '{% url 'connectpeer' %}',
data:{
"channel": channel,
"csrfmiddlewaretoken": csrftoken,
"user": user,
},
success: function (data) {
alert(data["response"])
}
});
...开发工具控制台上的输出:(您可以看到“打开了连接!”)onopen()事件侦听器中的字符串不打印,浏览器开发工具控制台中的dc.readyState命令只显示“连接”)

发布于 2021-08-30 06:01:09
您不是在交换冰候选人,而是打印更新的SDP。如果不交换冰的候选,连接就不会建立,数据通道也就不会打开。
https://stackoverflow.com/questions/68974865
复制相似问题