This commit is contained in:
2023-10-06 17:27:55 +08:00
parent 7f0cf13337
commit 5f5ed77ee8
1 changed files with 21 additions and 24 deletions

View File

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