[英]How do I initiate a WebRTC data channel?
我正在嘗試使用Web套接字在客戶端之間創建WebRTC數據通道。
我列出了一些ICE服務器
var rtcsettings = {
iceServers: [
{url: "stun:stun.ekiga.net"},
{url: "stun:stun.voipbuster.com"},
{url: "stun:stun.1.google.com:19302"},
]
};
然后有一個connect函數,它創建一個通道並提供並通過Web套接字發送它。
function(them) {
var pc = new RTCPeerConnection(rtcsettings);
self.channel = pc.createDataChannel("gamelink");
console.log(pc, self.channel);
self.peerconnection = pc;
pc.createOffer(function(offer) {
pc.setLocalDescription(new RTCSessionDescription(offer), function() {
self.socket.send(JSON.stringify({
"to": them,
"uuid": uuid,
"offer": offer,
}));
}, pc.close);
}, pc.close);
}
然后在另一端有一個回調,它將提議添加到其連接並發送響應。
它還為添加數據通道設置回調,但這永遠不會觸發。 我錯過了什么?
function (message){
var offer = message.offer;
var pc = new RTCPeerConnection(rtcsettings);
pc.ondatachannel = function(ch) {
self.channel = ch;
console.log(self.channel);
}
console.log(pc);
pc.setRemoteDescription(new RTCSessionDescription(offer), function() {
pc.createAnswer(function(answer) {
pc.setLocalDescription(new RTCSessionDescription(answer), function() {
self.socket.send(JSON.stringify({
"to": message.uuid,
"uuid": uuid,
"answer": answer,
}));
}, pc.close);
}, pc.close);
}, pc.close);
self.peerconnection = pc;
}
然后最后在啟動器上有另一個回調,它將響應描述符添加到其連接。
function(message) {
self.peerconnection.setRemoteDescription(
new RTCSessionDescription(message.answer),
function() { },
self.peerconnection.close);
}
除了套接字內容和數據通道內容之外的所有代碼幾乎都是從MDN Basic Usage頁面中逐字記錄的。
我正在使用localhost上的Chrome進行測試,因此防火牆應該不是問題。
交換發生后,兩個連接都有一個本地和遠程描述符集。 數據通道readyState
正在connecting
。 PeerConnection的iceConnectionState
是new
,其signalingState
是stable
。
缺少了什么?
你需要處理ICE候選人。
在攻防兩端,需要有這樣的回調:
pc.onicecandidate = function(e) {
if(e.candidate) {
self.socket.send(JSON.stringify({
"to": message.uuid,
"uuid": uuid,
"candidate": e.candidate,
}));
}
};
和一個處理程序
callbacks["candidate"] = function(message) {
console.log(message)
self.peerconnection.addIceCandidate(new RTCIceCandidate(message.candidate));
}
將這些設置添加到RTCPeerConnection
var optionalRtpDataChannels = {
optional: [{RtpDataChannels: true}]
};
var pc = new RTCPeerConnection(rtcsetting, optionalRtpDataChannels);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.