当前位置: 首页 > news >正文

WebRTC音视频开发读书笔记(六)

数据通道不仅可以发送文本消息, 还可以发送图片、二进制文件,将其类型binaryType属性设置成arraybuffer类型即可.

九\、文件传输

1、文件传输流程

(1)使用表单file打开本地文件

(2)使用FileReader读取文件的二进制数据

 (3)创建对等连接,本地连接及远端连接

  (4)创建发送数据通道

  (5)创建接收数据通道

   (6)将读取的二进制数据 切割成一个个切片,然后使用数据通道的send方法发送数据 。

  (7)使用接收数据通道二进制数据 将其放入数据缓存

  (8)根据数据缓存生成Blob 文件

   (10)生成文件连接并提供下载。

读取流程中文件二进制数据使用FileReader对象,还需要对数据进行切片处理,在接收方法中使用缓存将接收的数据缓存起来,最后生成blob下载文件。处理流程如下所示:

2、FileReader

FileReader对象允许Web应用程序异步读取存储在用户计算机上的文件内容。常用事件如下所示:

使用File或Blob对象指定要读取的文件或数据,当监听到load事件后,即可通过事件的结果属性拿到数据,然后使用发送通道的send方法将数据发送出去。代码如下:

sendChannel.send(e.target.result)

读取二进制数据可以使用FileReader的readAsArrayBuffer方法,结果为ArrayBuffer对象。还有其它处理方法,如下所示:

读取数据 时需要将数据分成一段一段的,然后发送,接收时再按顺序读取到数据缓存中,数据流的走向如图所示:

上图中数据块叫做Chunk,DataChannel每次发送的数据即为Chunk,  使用对象的slice方法按顺序切割 出数据块。如下面代码所示:

let slice=file.slice(offset,offset+chunksize)

假设chunksize的大小为16348,整个文件的数据块如下所示:

3、发送文件示例

本示例为文件具休步骤如下:

(1)首先在界面上添加input,类型为file,用于选择并读取文件,progress两个,分别用于发送及接收文件进度展示。

 (2)创建本地和远端连接,发送和接收数据通道,发送和接收通道的数据类型设置为arraybuffer。

  (3)建立本地和远端连接

  (4)实例化FileReader对象,并添加如下事件:

                      error:  读取文件错误

                     abort:  读取文件取消

                      load:  文件加载完成

         load事件表示数据已经准备好,可以进行切割发送,具体处理逻辑如下所示:

//监听load事件
fileReader.addEventListener('load',(e)=>{...//发送文件数据sendChannel.send(e.target.result);//偏移量offer+=e.target.result.byteLength;...//判断偏移量是否小于文件大小if(offer<file.size){//继续读取readSlice(offser)}
});//读取切片大小
let readSlice=(o)=>{...//开始切片let slice=file.slice(offset ,o+chunksize);//读取二进制数据  fileReader.readAsArrayBuffer(slice);}

   (5)数据接收处理,将收到第一个数据放入receiveBuffer缓存,处理逻辑如下所示:

//接收消息处理
onReceiveMessageCallback=(event)=>{
//将接收的数据添加到接收缓存里receiveBuffer.push(event.data);
//设置当前接收文件的大小receivedSize+=event.data.byteLength;...const file=fileInput.files[0];
//判断当前接收的文件大小是否等于文件的大小
if(receivedSize===file.size){//根据缓存生成Blob文件const received=new Blob(receiveBuffer)//将缓存数据设置为空receiveBuffer=[];...//创建下载文件对象及连接...}
}

完整代码如下:

import React from "react";
import { Button } from "antd";//本地连接对象
let localConnection;
//远端连接对象
let remoteConnection;
//发送通道
let sendChannel;
//接收通道
let receiveChannel;
//文件读取
let fileReader;
//接收数据缓存
let receiveBuffer = [];
//接收到的数据大小
let receivedSize = 0;
//文件选择
let fileInput;
//发送进度条
let sendProgress;
//接收进度条
let receiveProgress;/*** 数据通道发送文件示例*/
class DataChannelFile extends React.Component {componentDidMount() {sendProgress =document.getElementById('sendProgress') receiveProgress =document.getElementById('receiveProgress')fileInput = document.getElementById('fileInput');//监听change事件,判断文件是否选择fileInput.addEventListener('change', async () => {const file = fileInput.files[0];if (!file) {console.log('没有选择文件');} else {console.log('选择的文件是:' + file.name);}});}//建立对等连接并发送文件startSendFile = async () => {//创建RTCPeerConnection对象localConnection = new RTCPeerConnection();console.log('创建本地PeerConnection成功:localConnection');//监听返回的Candidate信息localConnection.addEventListener('icecandidate', this.onLocalIceCandidate);//实例化发送通道sendChannel = localConnection.createDataChannel('webrtc-datachannel');//数据类型为二进制sendChannel.binaryType = 'arraybuffer';//onopen事件监听sendChannel.addEventListener('open', this.onSendChannelStateChange);//onclose事件监听sendChannel.addEventListener('close', this.onSendChannelStateChange);//创建RTCPeerConnection对象remoteConnection = new RTCPeerConnection();console.log('创建本地PeerConnection成功:remoteConnection');//监听返回的Candidate信息remoteConnection.addEventListener('icecandidate', this.onRemoteIceCandidate);//远端连接数据到达事件监听remoteConnection.addEventListener('datachannel', this.receiveChannelCallback);//监听ICE状态变化localConnection.addEventListener('iceconnectionstatechange', this.onLocalIceStateChange);//监听ICE状态变化remoteConnection.addEventListener('iceconnectionstatechange', this.onRemoteIceStateChange);try {console.log('localConnection创建提议Offer开始');//创建提议Offerconst offer = await localConnection.createOffer();//创建Offer成功await this.onCreateOfferSuccess(offer);} catch (e) {//创建Offer失败this.onCreateSessionDescriptionError(e);}}//创建会话描述错误onCreateSessionDescriptionError = (error) => {console.log(`创建会话描述SD错误: ${error.toString()}`);}//创建提议Offer成功onCreateOfferSuccess = async (desc) => {//localConnection创建Offer返回的SDP信息console.log(`localConnection创建Offer返回的SDP信息\n${desc.sdp}`);console.log('设置localConnection的本地描述start');try {//设置localConnection的本地描述await localConnection.setLocalDescription(desc);this.onSetLocalSuccess(localConnection);} catch (e) {this.onSetSessionDescriptionError();}console.log('remoteConnection开始设置远端描述');try {//设置remoteConnection的远端描述await remoteConnection.setRemoteDescription(desc);this.onSetRemoteSuccess(remoteConnection);} catch (e) {//创建会话描述错误this.onSetSessionDescriptionError();}console.log('remoteConnection开始创建应答Answer');try {//创建应答Answerconst answer = await remoteConnection.createAnswer();//创建应答成功await this.onCreateAnswerSuccess(answer);} catch (e) {//创建会话描述错误this.onCreateSessionDescriptionError(e);}}//设置本地描述完成onSetLocalSuccess = (pc) => {console.log(`${this.getName(pc)}设置本地描述完成:setLocalDescription`);}//设置远端描述完成onSetRemoteSuccess = (pc) => {console.log(`${this.getName(pc)}设置远端描述完成:setRemoteDescription`);}//设置描述SD错误onSetSessionDescriptionError = (error) => {console.log(`设置描述SD错误: ${error.toString()}`);}getName = (pc) => {return (pc === localConnection) ? 'localConnection' : 'remoteConnection';}//创建应答成功onCreateAnswerSuccess = async (desc) => {//输出SDP信息console.log(`remoteConnection的应答Answer数据:\n${desc.sdp}`);console.log('remoteConnection设置本地描述开始:setLocalDescription');try {//设置remoteConnection的本地描述信息await remoteConnection.setLocalDescription(desc);this.onSetLocalSuccess(remoteConnection);} catch (e) {this.onSetSessionDescriptionError(e);}console.log('localConnection设置远端描述开始:setRemoteDescription');try {//设置localConnection的远端描述,即remoteConnection的应答信息await localConnection.setRemoteDescription(desc);this.onSetRemoteSuccess(localConnection);} catch (e) {this.onSetSessionDescriptionError(e);}}//Candidate事件回调方法onLocalIceCandidate = async (event) => {try {if (event.candidate) {//将会localConnection的Candidate添加至remoteConnection里await remoteConnection.addIceCandidate(event.candidate);this.onAddIceCandidateSuccess(remoteConnection);}} catch (e) {this.onAddIceCandidateError(remoteConnection, e);}console.log(`IceCandidate数据:\n${event.candidate ? event.candidate.candidate : '(null)'}`);}//Candidate事件回调方法onRemoteIceCandidate = async (event) => {try {if (event.candidate) {//将会remoteConnection的Candidate添加至localConnection里await localConnection.addIceCandidate(event.candidate);this.onAddIceCandidateSuccess(localConnection);}} catch (e) {this.onAddIceCandidateError(localConnection, e);}console.log(`IceCandidate数据:\n${event.candidate ? event.candidate.candidate : '(null)'}`);}//添加Candidate成功onAddIceCandidateSuccess = (pc) => {console.log(`${this.getName(pc)}添加IceCandidate成功`);}//添加Candidate失败onAddIceCandidateError = (pc, error) => {console.log(`${this.getName(pc)}添加IceCandidate失败: ${error.toString()}`);}//监听ICE状态变化事件回调方法onLocalIceStateChange = (event) => {console.log(`localConnection连接的ICE状态: ${localConnection.iceConnectionState}`);console.log('ICE状态改变事件: ', event);}//监听ICE状态变化事件回调方法onRemoteIceStateChange = (event) => {console.log(`remoteConnection连接的ICE状态: ${remoteConnection.iceConnectionState}`);console.log('ICE状态改变事件: ', event);}//关闭数据通道closeChannel = () => {console.log('关闭数据通道');sendChannel.close();if (receiveChannel) {receiveChannel.close();}//关闭localConnectionlocalConnection.close();//关闭remoteConnectionremoteConnection.close();//localConnection置为空localConnection = null;//remoteConnection置为空remoteConnection = null;}//发送数据sendData = () => {let file = fileInput.files[0];console.log(`文件是: ${[file.name, file.size, file.type].join(' ')}`);//设置发送进度条的最大值sendProgress.max = file.size;//设置接收进度条的最大值receiveProgress.max = file.size;//文件切片大小,即每次读取的文件大小let chunkSize = 16384;//实例化文件读取对象fileReader = new FileReader();//偏移量可用于表示进度let offset = 0;//监听error事件fileReader.addEventListener('error', (error) => {console.error('读取文件出错:', error)});//监听abort事件fileReader.addEventListener('abort', (event) => {console.log('读取文件取消:', event)});//监听load事件fileReader.addEventListener('load', (e) => {console.log('文件加载完成 ', e);//使用发送通道开始发送文件数据sendChannel.send(e.target.result);//使用文件二进制数据长度作为偏移量offset += e.target.result.byteLength;//使用偏移量作为发送进度sendProgress.value = offset;console.log('当前文件发送进度为:', offset);//判断偏移量是否小于文件大小if (offset < file.size) {//继续读取readSlice(offset);}});//读取切片大小let readSlice = (o) => {console.log('readSlice ', o);//将文件的某一段切割下来,从offset到offset + chunkSize位置切下let slice = file.slice(offset, o + chunkSize);//读取切片的二进制数据fileReader.readAsArrayBuffer(slice);};//首次读取0到chunkSize大小的切片数据readSlice(0);}//接收通道数据到达回调方法receiveChannelCallback = (event) => {//实例化接收通道receiveChannel = event.channel;//数据类型为二进制receiveChannel.binaryType = 'arraybuffer';//接收消息事件监听receiveChannel.onmessage = this.onReceiveMessageCallback;//onopen事件监听receiveChannel.onopen = this.onReceiveChannelStateChange;//onclose事件监听receiveChannel.onclose = this.onReceiveChannelStateChange;receivedSize = 0;}//接收消息处理onReceiveMessageCallback = (event) => {console.log(`接收的数据 ${event.data.byteLength}`);//将接收到的数据添加到接收缓存里receiveBuffer.push(event.data);//设置当前接收文件的大小receivedSize += event.data.byteLength;//使用接收文件的大小表示当前接收进度receiveProgress.value = receivedSize;const file = fileInput.files[0];//判断当前接收的文件大小是否等于文件的大小if (receivedSize === file.size) {//根据缓存数据生成Blob文件const received = new Blob(receiveBuffer);//将缓存数据置为空receiveBuffer = [];//获取下载连接对象let download = document.getElementById('download');//创建下载文件对象及链接download.href = URL.createObjectURL(received);download.download = file.name;download.textContent = `点击下载'${file.name}'(${file.size} bytes)`;download.style.display = 'block';}}//发送通道状态变化onSendChannelStateChange = () => {const readyState = sendChannel.readyState;console.log('发送通道状态: ' + readyState);if (readyState === 'open') {this.sendData();}}//接收通道状态变化onReceiveChannelStateChange = () => {const readyState = receiveChannel.readyState;console.log('接收通道状态:' + readyState);}//取消发送文件cancleSendFile = () => {if (fileReader && fileReader.readyState === 1) {console.log('取消读取文件');fileReader.abort();}}render() {return (<div className="container"><div><form id="fileInfo"><input type="file" id="fileInput" name="files" /></form><div><h2>发送</h2><progress id="sendProgress" max="0" value="0" style={{width:'500px'}}></progress></div><div><h2>接收</h2><progress id="receiveProgress" max="0" value="0" style={{width:'500px'}}></progress></div></div><a id="download"></a><div><Button onClick={this.startSendFile} style={{ marginRight: "10px" }}>发送</Button><Button onClick={this.cancleSendFile} style={{ marginRight: "10px" }}>取消</Button><Button onClick={this.closeChannel} style={{ marginRight: "10px" }}>关闭</Button></div></div>);}
}
//导出组件
export default DataChannelFile;

相关文章:

  • Go 语言并发--高级概述
  • 11.4k star! 部署清华开源的ChatGLM3,用私有化大模型无缝替换openai
  • 探索Python的工业通信之光:pymodbus的奇妙之旅
  • STM32时钟树配置
  • linux dig域名DNS 查询与iptables域名ip访问流量限制
  • 元素设置了sticky粘性布局后,关于滚动后怎么样让这个元素自动添加阴影,我用自定义指令实现
  • 4.3 数据操作语言(DML):增删改查操作
  • 牛客网SQL进阶135 :每个6/7级用户活跃情况
  • 【c++】通过Privilege类来保护数据
  • 【layui】layer弹出图片层(开启图片旋转 放大 缩小 还原)
  • PostgreSQL常用命令,启动连接,pg_dump导入导出
  • Python模块篇(五)
  • 2408d,加@GC作为函数属性
  • Java基于数据库、乐观锁、悲观锁、Redis、Zookeeper分布式锁的简单案例实现(保姆级教程)
  • 面试题:MQ
  • [译] React v16.8: 含有Hooks的版本
  • 【347天】每日项目总结系列085(2018.01.18)
  • 【跃迁之路】【641天】程序员高效学习方法论探索系列(实验阶段398-2018.11.14)...
  • CAP理论的例子讲解
  • es6要点
  • JS基础之数据类型、对象、原型、原型链、继承
  • Leetcode 27 Remove Element
  • LintCode 31. partitionArray 数组划分
  • MySQL常见的两种存储引擎:MyISAM与InnoDB的爱恨情仇
  • PAT A1017 优先队列
  • Python 反序列化安全问题(二)
  • react 代码优化(一) ——事件处理
  • SegmentFault 社区上线小程序开发频道,助力小程序开发者生态
  • Spring Cloud Feign的两种使用姿势
  • XForms - 更强大的Form
  • 从零开始学习部署
  • 复杂数据处理
  • 构建工具 - 收藏集 - 掘金
  • 官方解决所有 npm 全局安装权限问题
  • 回顾2016
  • 容器服务kubernetes弹性伸缩高级用法
  • 使用 Xcode 的 Target 区分开发和生产环境
  • 线上 python http server profile 实践
  • 正则与JS中的正则
  • 《码出高效》学习笔记与书中错误记录
  • 【干货分享】dos命令大全
  • 正则表达式-基础知识Review
  • ​草莓熊python turtle绘图代码(玫瑰花版)附源代码
  • #我与Java虚拟机的故事#连载17:我的Java技术水平有了一个本质的提升
  • $ git push -u origin master 推送到远程库出错
  • ( )的作用是将计算机中的信息传送给用户,计算机应用基础 吉大15春学期《计算机应用基础》在线作业二及答案...
  • ( 10 )MySQL中的外键
  • (Charles)如何抓取手机http的报文
  • (js)循环条件满足时终止循环
  • (附源码)计算机毕业设计SSM基于健身房管理系统
  • (附源码)计算机毕业设计大学生兼职系统
  • (一)Mocha源码阅读: 项目结构及命令行启动
  • (一)模式识别——基于SVM的道路分割实验(附资源)
  • (中等) HDU 4370 0 or 1,建模+Dijkstra。
  • (转) SpringBoot:使用spring-boot-devtools进行热部署以及不生效的问题解决