From d3011d92808df21efbc8c6b0364cc75f503b4359 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=A7=89?= Date: Fri, 6 Oct 2023 16:06:17 +0800 Subject: [PATCH] =?UTF-8?q?=E8=AF=A1...?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- public/entanglement.js | 22 ++++++++++++++++++--- public/test.html | 45 ++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 62 insertions(+), 5 deletions(-) diff --git a/public/entanglement.js b/public/entanglement.js index 7cd3dd4..ba08a73 100644 --- a/public/entanglement.js +++ b/public/entanglement.js @@ -43,7 +43,7 @@ export default class Entanglement { console.debug('发送给', user.name, 'offer') const pc = await this.__create_webrtc(user) const offer = await pc.createOffer() - pc.setLocalDescription(offer) + await pc.setLocalDescription(offer) this.ws.send(JSON.stringify({ type: 'offer', user, offer })) return { ...user, webrtc: pc } })) @@ -60,7 +60,7 @@ export default class Entanglement { if (data.type === 'offer') { console.debug(data.user.name, '发来 offer') const pc = await this.__create_webrtc(data.user) - pc.setRemoteDescription(data.offer) + await pc.setRemoteDescription(data.offer) const answer = await pc.createAnswer() await pc.setLocalDescription(answer) this.ws.send(JSON.stringify({ type: 'answer', user: data.user, answer })) @@ -129,12 +129,28 @@ export default class Entanglement { console.log(data.user.name, '通道', event.channel.label, '发生错误') } } + // 创建数据通道 + const channel = pc.createDataChannel('json', { reliable: true }) + channel.onopen = () => { + console.log('打开数据通道') + channel.send(JSON.stringify({ name: 'sato', hello: 'world' })) + } + channel.onmessage = event => { + console.log('收到数据通道消息', event.data) + } + channel.onclose = () => { + console.log('关闭数据通道') + } + channel.onerror = () => { + console.log('数据通道发生错误') + } return pc } // 向所有在线的用户广播消息(webrtc) send_all(channel_name, data) { console.log('向', channel_name, '频道广播消息:', data) + console.log('在线用户:', this.users) this.users.filter(user => { const status = user.webrtc.iceConnectionState return status === 'connected' || status === 'completed' @@ -153,7 +169,7 @@ export default class Entanglement { set: (target, key, value) => { if (!Array.isArray(target) || key !== 'length') { console.log('对象被修改', [...path, key], value) - this.send_all(name, this.store[name]) // 向所有在线的用户广播消息 + this.send_all(name, { key: [...path, key], value }) // 向所有在线的用户广播消息 } return Reflect.set(target, key, value) }, diff --git a/public/test.html b/public/test.html index 75fed4e..4f6bfd2 100644 --- a/public/test.html +++ b/public/test.html @@ -13,16 +13,57 @@ - + \ No newline at end of file