webRTC之 DataChannel 文件传输
前面介绍了 webrtc 音视频流的通信, 根据自己粗浅的理解简单介绍了下, 今天花了点时间看了下DataChannel, 如何通过rtc发送文件,开始的步骤还是一样的 通过websocket 把 offeranswericecandidate 点对点建立这次的主要提下createDataChannel本地端创建sendChannel = local.createDataChan...
·
前面介绍了 webrtc 音视频流的通信, 根据自己粗浅的理解简单介绍了下, 今天花了点时间看了下DataChannel, 如何通过rtc发送文件,开始的步骤还是一样的 通过websocket 把 offer answer icecandidate 点对点建立
这次的主要提下 createDataChannel
本地端创建
sendChannel = local.createDataChannel(name, options);
sendChannel.addEventListener('open', onSendChannelStateChange); //打开之后才可以传输数据
sendChannel.addEventListener('close', onSendChannelStateChange);
sendChannel.send(JSON.stringify({
name: file.name,
type: file.type,
size: file.size
}));
//也可以发送arraybuffer;
fileReader.onload = (e) => { sendChannel.send(e.target.result)};
参数可以参考 https://developer.mozilla.org/zh-CN/docs/Web/API/RTCPeerConnection/createDataChannel#RTCDataChannelInit_dictionary
remote.addEventListener('datachannel', callback);
//接受data
function callback(event){
// console.log('recive', event);
receiveChannel = event.channel;
receiveChannel.binaryType = 'arraybuffer';
receiveChannel.onmessage = onReceiveMessageCallback;
}
function onReceiveMessageCallback(event) {
if (typeof event.data == 'string') {
rcname = JSON.parse(event.data)['name'];
rcsize = JSON.parse(event.data)['size'];
document.getElementById('box').style.display = 'none';
document.getElementById('msg').style.display = 'block';
document.getElementById('msg').innerHTML = "<p>文件共计"+(rcsize/1024/1024).toFixed(2)+"MB</p>";
return;
};
receiveBuffer.push(event.data);
receivedSize += event.data.byteLength;
document.querySelector('#bars p').style.width = (receivedSize/rcsize) * 100 +"%"
if (receivedSize == rcsize) {
let resultfile = new Blob(receiveBuffer);
let url = URL.createObjectURL(resultfile);
receivedSize = 0;
let a = document.createElement('a');
a.download = rcname;
a.innerHTML = '点击保存';
a.href=url;
receiveChannel.close();
document.getElementById('msg').appendChild(a);
}
}
发送成功
更多推荐
已为社区贡献1条内容
所有评论(0)