我正在使用SimpleSignalling 服务器连接两个对等点。基本流程是:
PubNub广播节点 A 的创建
pubnub.subscribe( {
channel : 'mimis/peer/awaken',
message : function( msg ) {
var dest_uid = msg
if( server.uid() != dest_uid ) {
onawaken( dest_uid )
}
},
} )
对等 B 创建一个新的 PeerConnection
function onawaken( uid ) {
var servers = null
connections[uid] = new webkitRTCPeerConnection( servers,
{ optional: [{ RtpDataChannels: true }] } )
function gotCandidate( event ) {
if( event.candidate ) {
server.send( event.candidate, uid, server.room() )
}
}
connections[uid].onicecandidate = gotCandidate
try {
channels[uid] = connections[uid].createDataChannel( "mimisChannel",
{ reliable: false } )
} catch (e) {
console.error( 'Failed to create data channel. ' +
'You need Chrome M25 or later with RtpDataChannel enabled' )
}
function gotLocalDescription( desc ) {
connections[uid].setLocalDescription( desc )
server.send( desc, uid, server.room() )
}
connections[uid].createOffer( gotLocalDescription )
}
PeerConnection 创建响应
function onoffer( offer, uid ) {
connections[uid] = new webkitRTCPeerConnection( servers,
{ optional: [{ RtpDataChannels: true }] } )
function gotRemoteDescription( desc ) {
connections[uid].setRemoteDescription( desc )
server.send( desc, uid, server.room() )
}
connections[uid].createAnswer( gotRemoteDescription )
function gotReceiveChannel( event ) {
channels[uid] = event.channel
}
connections[uid].ondatachannel = gotReceiveChannel
}
ICE 候选是作为来自 SimpleSignaling 服务器的消息接收的。
server.onmessage = function( msg, uid, room ) {
if( msg.type == 'offer' ) {
onoffer( msg, uid )
} else if( msg.candidate ) {
try {
connections[uid].addIceCandidate( msg )
} catch( e ) {
console.error( 'connections[uid].addIceCandidate', e )
}
} else {
console.warn( 'server.onmessage: Unknown message type', msg )
}
}
onawaken
onicecandidate
处理程序似乎执行正确。当打开两个选项卡时,第二个选项卡将接收 JSON 候选对象。当我将它们传递给 时connections[uid].addIceCandidate
,我收到错误 `TypeMismatchError: DOM Exception 17.
传递给的内容addIceCandidate
必须是RTCIceCandidate
. 最终代码如下所示:
server.onmessage = function( msg, uid, room ) {
var candidate = new RTCIceCandidate( msg )
connections[uid].addIceCandidate( candidate )
}
现在我明白了SyntaxError: DOM Exception 12
。理论上这是因为我之前打过电话addIceCandidate
setRemoteDescription
。我有setRemoteDescription
in createAnswer
,但回调永远不会被执行。
onoffer
我补充说:
connections[uid].setRemoteDescription( new RTCSessionDescription( offer ) )
这清除了语法错误。ICE 消息现在已成功发送,但从connections[uid].ondatachannel
未被调用。