From 35cde09bb0d617620f6c6886d373f74911b265b8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=A7=89?= Date: Fri, 6 Oct 2023 15:19:43 +0800 Subject: [PATCH] =?UTF-8?q?=E5=8D=8F=E5=95=86=E6=96=B0=E7=9A=84=E4=BC=9A?= =?UTF-8?q?=E8=AF=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- public/entanglement.js | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/public/entanglement.js b/public/entanglement.js index d1f26d0..7cd3dd4 100644 --- a/public/entanglement.js +++ b/public/entanglement.js @@ -73,10 +73,10 @@ export default class Entanglement { await pc.setRemoteDescription(data.answer) return } - if (data.type === 'icecandidate') { - console.debug(data.user.name, '发来 icecandidate 候选通道') + if (data.type === 'candidate') { + console.debug(data.user.name, '发来 candidate 候选通道') const pc = this.users.find(user => user.id === data.user.id).webrtc - await pc.addIceCandidate(data.icecandidate) + await pc.addIceCandidate(data.candidate) return } console.error('收到未知数据:', data) @@ -86,12 +86,14 @@ export default class Entanglement { async __create_webrtc(user) { const pc = new RTCPeerConnection(this.options) + // 当有新的媒体流加入时触发 pc.onicecandidate = (event) => { if (event.candidate) { - console.debug(user.name, '发出 icecandidate 候选通道') - this.ws.send(JSON.stringify({ type: 'icecandidate', user, icecandidate: event.candidate })) + console.debug(user.name, '发出 candidate 候选通道') + this.ws.send(JSON.stringify({ type: 'candidate', user, candidate: event.candidate })) } } + // 当连接状态发生改变时触发 pc.oniceconnectionstatechange = (event) => { if (webrtc.iceConnectionState === 'disconnected' || webrtc.iceConnectionState === 'failed') { console.error(data.name, '需要添加新的 candidate') @@ -99,12 +101,18 @@ export default class Entanglement { console.debug(data.name, 'WebRTC 连接已经建立成功') } } - pc.onnegotiationneeded = (event) => { + // 协商新的会话, 建立初始连接或在网络条件发生变化后重新协商连接 + pc.onnegotiationneeded = async (event) => { console.log('onnegotiationneeded', event) + const offer = await pc.createOffer() + await pc.setLocalDescription(offer) + this.ws.send(JSON.stringify({ type: 'offer', user, offer })) } + // 当有新的媒体流加入时触发 pc.ontrack = (event) => { console.log('ontrack', event) } + // 当有新的数据通道加入时触发 pc.ondatachannel = event => { console.log(data.user.name, '建立', event.channel.label, '通道') event.channel.onmessage = event => {