diff --git a/public/entanglement.js b/public/entanglement.js index c79efb5..e946240 100644 --- a/public/entanglement.js +++ b/public/entanglement.js @@ -1,19 +1,13 @@ export default class Entanglement { - constructor({ options, server }) { + constructor({ options }) { this.event = {} this.options = options - this.server = server - this.channels = {} - this.client = {} - this.store = {} this.users = [] - this.account = {} + this.channels = [{ name: 'json' }] this.ws = this.__create_websocket() } - // 当创建一个对象时,会调用这个方法 - // 当创建一个对象时,所有连接在一起的终端都会同步这个对象 - // 并不是所有的终端都会监听全局变化, 因此需要在这里注册监听(频道) + async __create_webrtc(user) { const pc = new RTCPeerConnection(this.options) // 当有新的媒体流加入时触发 @@ -60,20 +54,23 @@ export default class Entanglement { } } // 创建数据通道 - 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('数据通道发生错误') - } + user.channels = this.channels.map(item => { + const channel = pc.createDataChannel(item.name, { 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 { channel, ...item } + }) return pc } @@ -156,7 +153,7 @@ export default class Entanglement { return status === 'connected' || status === 'completed' }).forEach(user => { console.log('向', user.name, '发送', channel_name, '频道消息:', data) - const channel = user.webrtc.createDataChannel(channel_name, { reliable: true }) + const channel = user.channels.find(item => item.name === channel_name).channel channel.onopen = () => channel.send(JSON.stringify(data)) }) }