知识补充
webRTC 基本知识前几天刚学习
首次接触从什么地方开始?
或许刚开始接触的时候会有一大批陌生名词,但最主要的是一个本地video,以及远端动态的video框然后做一些逻辑处理,实现视频多人通话。
核心类RTCPeerConnection
一个基本的RTCPeerConnection使用需要协调本地机器以及远端机器的连接,它可以通过在两台机器间生成Session Description的数据交换协议来实现。呼叫方发送一个offer(请求),被呼叫方发出一个answer(应答)来回答请求。双方-呼叫方以及被呼叫方,最开始的时候都要建立他们各自的RTCPeerConnection对象。
创建流程
-
加入房间
socket.onopen = function () { socket.send( JSON.stringify({ eventName: '__join', data: { room: room, }, }) ) that.emit('socket_opened', socket) } -
实例化RTCPeerConnection
var pc = new PeerConnection(iceServer) this.peerConnections[socketId] = pc pc.onicecandidate = function (evt) { if (evt.candidate) that.socket.send( JSON.stringify({ eventName: '__ice_candidate', data: { id: evt.candidate.sdpMid, label: evt.candidate.sdpMLineIndex, sdpMLineIndex: evt.candidate.sdpMLineIndex, candidate: evt.candidate.candidate, socketId: socketId, }, }) ) that.emit('pc_get_ice_candidate', evt.candidate, socketId, pc) }创建pc上的一些事件监听
-
发送offer
setLocalDescription
pcCreateOfferCbGen = function (pc, socketId) { return function (session_desc) { pc.setLocalDescription(session_desc) that.socket.send( JSON.stringify({ eventName: '__offer', data: { sdp: session_desc, socketId: socketId, }, }) ) } }, -
发送answer
setRemoteDescription
pc.setRemoteDescription(new nativeRTCSessionDescription(sdp)) pc.createAnswer( function (session_desc) { pc.setLocalDescription(session_desc) that.socket.send( JSON.stringify({ eventName: '__answer', data: { socketId: socketId, sdp: session_desc, }, }) ) } -
ice_candidate交换
var candidate = new nativeRTCIceCandidate(data) var pc = that.peerConnections[data.socketId] if (!pc) { //|| !pc.remoteDescription.type console.log('remote not set!') } pc.addIceCandidate(candidate)
初次创建连接打印顺序
小结
很多知识点也是从MDN开始看起来学习的,抓住这几个最主要的流程去理解整个过程,有几个坑花了很多时间才解决掉,比如禁止本地用户推流, 下章记录踩坑。