profile 分离

This commit is contained in:
2023-10-19 06:55:54 +08:00
parent 23a0c60ad0
commit edae22db79
2 changed files with 170 additions and 36 deletions

View File

@ -67,14 +67,14 @@ export default class ClientList {
iceTransportPolicy: 'all', // 使用所有可用的候选者
bundlePolicy: 'max-bundle',// 将所有媒体流捆绑在一起,以最大程度地提高性能和减少延迟
sctp: {
maxMessageSize: 1024 * 64, // 64KB
maxRetransmits: 10, // 最大重传次数
maxPacketLifeTime: 3000, // 最大生存时间
renegotiationTimeout: 1000, // 重协商超时时间
redeliveryTimeout: 1000, // 重传超时时间
redeliveryTime: 1000, // 重传时间
reliability: 'reliable', // 可靠传输
ordered: true, // 有序传输
//maxMessageSize: 1024 * 64, // 64KB
//maxRetransmits: 10, // 最大重传次数
//maxPacketLifeTime: 3000, // 最大生存时间
//renegotiationTimeout: 3000, // 重协商超时时间
//redeliveryTimeout: 1000, // 重传超时时间
//redeliveryTime: 1000, // 重传时间
//reliability: 'reliable', // 可靠传输
//ordered: true, // 有序传输
}
})
webrtc.ondatachannel = ({ channel }) => {
@ -124,8 +124,15 @@ export default class ClientList {
}
}
const channels = Object.entries(this.channels).map(([name, callback]) => {
const channel = webrtc.createDataChannel(name, { reliable: true })
return channel
const dc = webrtc.createDataChannel(name, {
reliability: 'reliable', // 可靠传输
reliable: true, // 可靠传输
ordered: true, // 有序传输
//maxMessageSize: 64, // 64KB
//maxRetransmits: 10, // 最大重传次数
//maxPacketLifeTime: 3000, // 最大生存时间
})
return dc
})
return { webrtc, channels }
}
@ -349,6 +356,48 @@ export default class ClientList {
ch.send(data)
})
}
// 通过指定通道发送数据(单播, 自动分片)
sendto2(id, name, data) {
console.log('发送数据:', name)
const client = this.clientlist.find(client => client.id === id)
if (!client) {
console.error('客户端不存在:', id)
return
}
if (!client.channels.find(ch => ch.label === name)) {
console.error('通道不存在:', name)
return
}
client.channels.filter(ch => ch.label === name).forEach(async ch => {
console.log('发送数据:', name, ch.label)
// 等待 datachannel 打开(临时解决方案)
while (ch.readyState !== 'open') {
await new Promise(resolve => setTimeout(resolve, 100))
}
console.log('发送数据:', name, ch.label, ch.readyState)
// 将数据转换为arraybuffer
const buffer = new ArrayBuffer(data.length)
const view = new Uint8Array(buffer)
for (let i = 0; i < data.length; i++) {
view[i] = data.charCodeAt(i) & 0xff
}
// 将数据分片发送
const CHUNK_SIZE = 16 * 1024; // 16KB
for (let i = 0; i < buffer.byteLength; i += CHUNK_SIZE) {
const chunk = view.subarray(i, i + CHUNK_SIZE)
ch.send(chunk)
console.log('缓冲区:', ch.bufferedAmount)
console.log('缓冲区剩余:', ch.bufferedAmountLowThreshold)
}
})
}
// 通过指定通道发送数据(广播)
send(name, data) {
this.clientlist.forEach(client => {

View File

@ -31,7 +31,7 @@ const list = (await musicStore.getAll()).map(item => {
})
// 读取本地用户名(本地缓存)
const name = localStorage.getItem('username') ?? '游客'
const name = localStorage.getItem('username') ?? ''
const avatar = localStorage.getItem('avatar') ?? '/favicon.ico'
@ -43,16 +43,14 @@ const clientList = new ClientList({
// 从列表中移除未缓存的此用户的音乐, 但可能多人都有此音乐且未缓存
// 因此每条音乐都要检查是否有其他用户也有此音乐, 如果有则不移除
const 此用户音乐 = client.musicList?.map(item => item.id) || []
const 无数据音乐 = musicList.list.filter(item => !item.arrayBuffer).filter(item => {
musicList.list.filter(item => !item.arrayBuffer).filter(item => {
return 此用户音乐.includes(item.id)
})
无数据音乐.forEach(item => {
}).forEach(item => {
const client = clientList.clientlist.find(client => {
return client.musicList.find(x => x.id === item.id)
})
if (!client) musicList.remove(item)
})
}
})
@ -179,35 +177,122 @@ clientList.setChannel('chat', {
}
})
const file_cache = []
// 与每个客户端都建立文件传输信道
clientList.setChannel('file', {
onopen: async (event, client) => {
//console.debug('打开信道', event.target.label)
//clientList.sendto(client.id, 'file', JSON.stringify({ id: '', start: 0, end: 16384 }))
//clientList.sendto(client.id, 'file', new ArrayBuffer(1024))
},
onmessage: async (event, client) => {
if (typeof event.data === 'string') {
console.log(client.name, '文件请求:', event.data)
const { id, start, end } = JSON.parse(event.data)
const file = file_cache.find(file => file.id === id)
const data = file.chunk.slice(start, end)
// 分片发送
const c = Math.ceil(file.chunk.length / (CHUNK_SIZE - (12 * 8)))
console.log('需要发送', c, '个分片')
const chunks = []
for (let i = 0; i < c; i++) {
const chunk = new ArrayBuffer(CHUNK_SIZE)
const view = new Uint32Array(chunk)
view[0] = file.id
view[1] = i * (CHUNK_SIZE - (12 * 8))
view[2] = (i + 1) * (CHUNK_SIZE - (12 * 8))
const data = new Uint8Array(chunk, 12)
data.set(new Uint8Array(file.chunk[i]))
chunks.push(chunk)
}
for (let i = 0; i < chunks.length; i++) {
const chunk = chunks[i]
console.log('发送分片', `${i + 1}/${chunks.length}`, chunk.byteLength)
clientList.sendto(client.id, 'file', chunk)
await new Promise((resolve) => setTimeout(resolve, DELAY))
}
console.log('文件发送完毕')
return
}
if (event.data instanceof ArrayBuffer) {
console.log(client.name, '发来文件:', event.data)
// 判断分片是哪个文件的
const file = file_cache.find(file => file.hash === event.target.label)
if (!file) {
console.log('未知文件:', event.target.label)
return
}
// 将分片保存到文件的分片列表中
file.chunk.push(event.data)
// 判断文件是否接收完毕
if (file.chunk.length === file.chunkNumber) {
console.log('文件接收完毕:', file)
// 将分片列表合并成一个文件
file.arrayBuffer = file.chunk.reduce((prev, curr) => appendBuffer(prev, curr))
// 将文件保存到本地
//fileStore.add(file)
// 将文件添加到音乐列表
//musicList.add(file)
// 将文件从缓存列表中移除
file_cache.splice(file_cache.indexOf(file), 1)
}
return
}
console.log('未知类型:', event)
}
})
// 与每个客户端都建立交换身份信道
clientList.setChannel('profile', {
onopen: async (event, client) => {
clientList.sendto(client.id, 'profile', JSON.stringify({
name: name,
avatar: avatar,
}))
},
onmessage: async (event, client) => {
const data = JSON.parse(event.data)
client.name = data.name
client.avatar = data.avatar
clientList.setAvatar({ id: client.id, ...data })
},
onclose: event => {
console.log('关闭信道', event.target.label)
},
onerror: event => {
console.error('信道错误', event.target.label, event.error)
}
})
// 与每个客户端都建立基本信道, 用于交换和调度信息
clientList.setChannel('base', {
onopen: async event => {
console.debug('打开信道', event.target.label, '广播请求音乐列表和身份信息')
clientList.send('base', JSON.stringify({ type: 'get_music_list' })) // 要求对方发送音乐列表
clientList.send('base', JSON.stringify({ type: 'get_user_profile' })) // 要求对方发送身份信息
//clientList.send('base', JSON.stringify({ type: 'get_user_profile' })) // 要求对方发送身份信息
},
onmessage: async (event, client) => {
const data = JSON.parse(event.data)
if (data.type === 'get_user_profile') {
console.log(client.name, '请求身份信息:', data)
// 包过大会导致发送失败, 因此需要分开发送
clientList.sendto(client.id, 'base', JSON.stringify({
type: 'set_user_profile',
name: name,
avatar: avatar,
}))
return
}
if (data.type === 'set_user_profile') {
console.log(client.name, '发来身份信息:', data)
console.log('将身份信息保存到本机记录:', client)
client.name = data.name
client.avatar = data.avatar
// 还需要更新组件的用户信息
console.log('更新组件的用户信息:', data, client)
clientList.setAvatar({ id: client.id, ...data })
return
}
//if (data.type === 'get_user_profile') {
// console.log(client.name, '请求身份信息:', data)
// clientList.sendto2(client.id, 'base', JSON.stringify({
// type: 'set_user_profile',
// name: name,
// avatar: avatar,
// }))
// return
//}
//if (data.type === 'set_user_profile') {
// console.log(client.name, '发来身份信息:', data)
// console.log('将身份信息保存到本机记录:', client)
// client.name = data.name
// client.avatar = data.avatar
// // 还需要更新组件的用户信息
// console.log('更新组件的用户信息:', data, client)
// clientList.setAvatar({ id: client.id, ...data })
// return
//}
if (data.type === 'get_image_list') {
// webrtc://用户@域名:端口/信道标识/资源ID
}