协商新的会话

This commit is contained in:
2023-10-06 15:19:43 +08:00
parent 526291bde8
commit 35cde09bb0
1 changed files with 14 additions and 6 deletions

View File

@ -73,10 +73,10 @@ export default class Entanglement {
await pc.setRemoteDescription(data.answer) await pc.setRemoteDescription(data.answer)
return return
} }
if (data.type === 'icecandidate') { if (data.type === 'candidate') {
console.debug(data.user.name, '发来 icecandidate 候选通道') console.debug(data.user.name, '发来 candidate 候选通道')
const pc = this.users.find(user => user.id === data.user.id).webrtc const pc = this.users.find(user => user.id === data.user.id).webrtc
await pc.addIceCandidate(data.icecandidate) await pc.addIceCandidate(data.candidate)
return return
} }
console.error('收到未知数据:', data) console.error('收到未知数据:', data)
@ -86,12 +86,14 @@ export default class Entanglement {
async __create_webrtc(user) { async __create_webrtc(user) {
const pc = new RTCPeerConnection(this.options) const pc = new RTCPeerConnection(this.options)
// 当有新的媒体流加入时触发
pc.onicecandidate = (event) => { pc.onicecandidate = (event) => {
if (event.candidate) { if (event.candidate) {
console.debug(user.name, '发出 icecandidate 候选通道') console.debug(user.name, '发出 candidate 候选通道')
this.ws.send(JSON.stringify({ type: 'icecandidate', user, icecandidate: event.candidate })) this.ws.send(JSON.stringify({ type: 'candidate', user, candidate: event.candidate }))
} }
} }
// 当连接状态发生改变时触发
pc.oniceconnectionstatechange = (event) => { pc.oniceconnectionstatechange = (event) => {
if (webrtc.iceConnectionState === 'disconnected' || webrtc.iceConnectionState === 'failed') { if (webrtc.iceConnectionState === 'disconnected' || webrtc.iceConnectionState === 'failed') {
console.error(data.name, '需要添加新的 candidate') console.error(data.name, '需要添加新的 candidate')
@ -99,12 +101,18 @@ export default class Entanglement {
console.debug(data.name, 'WebRTC 连接已经建立成功') console.debug(data.name, 'WebRTC 连接已经建立成功')
} }
} }
pc.onnegotiationneeded = (event) => { // 协商新的会话, 建立初始连接或在网络条件发生变化后重新协商连接
pc.onnegotiationneeded = async (event) => {
console.log('onnegotiationneeded', 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) => { pc.ontrack = (event) => {
console.log('ontrack', event) console.log('ontrack', event)
} }
// 当有新的数据通道加入时触发
pc.ondatachannel = event => { pc.ondatachannel = event => {
console.log(data.user.name, '建立', event.channel.label, '通道') console.log(data.user.name, '建立', event.channel.label, '通道')
event.channel.onmessage = event => { event.channel.onmessage = event => {