建立webrtc连接
TODO
利用webrtc点对点传输数据
场景:已经通过webrtc建立音视频流连接的两个客户端,可以用webrtc做点对点的数据传递
datachannel
创建方式:
peerCon.createDataChannel(label[,options])label:该通道的名称- options:可选参数
negotiated是否需要协商id若negotiated为true,则id必须填
label与id的区别:都是做id的功能,类似label(学校)与id(班级)。两者均有时,要学校label相同,且学校下的班级id也相同,才能互传数据
var localChannel = this.connection.createDataChannel("chat");
localChannel.onopen = function (event) {
channel.send("Hi you");
};
localChannel.onmessage = function (event) {
console.error(777, event.data);
};
获取远端的dataChannel
peerCon.ondatachannel=function(event){
var remoteChannel = event.channel;
console.log(event.channel.label) // chat,可以根据label做不同处理
remoteChannel.open = function(){
remoteChannel.send('hi, from remote')
}
remoteChannel.onmessage = function(){
console.error("on message", event.data);
}
}
假设有客户端A,客户端B,A中的remoteChannel实例就是B中的localChannel,同理,B中的remoteChannel就是A中的localChannel。
如果A要向B发消息,有两个方法:
- 在
A中调用remoteChannel.send('msg'),B可在localChannel.onmessage中接收到信息; - 在
A中调用localChannel.send('msg'),B可在remoteChannel.onmessage接收到信息
不同点在于,localChannel是固定了label的,而remoteChannel中的event.channel有其他属性
上述流程与
postMessage跨域方式相似。若网页A要向网页B(iframe中或window.open打开的的)传数据,需要在网页A中获取B的windowB,然后windowB.postMessage向网页B发送数据