ws断线重联

This commit is contained in:
2023-09-30 23:01:30 +08:00
parent 9181ba419e
commit 8711fa9555
1 changed files with 87 additions and 75 deletions

View File

@ -11,7 +11,10 @@ export default class ClientList {
this.ul = List({}) this.ul = List({})
document.body.appendChild(this.ul) document.body.appendChild(this.ul)
this.websocket.onmessage = async event => { // 连接 WebSocket
const linkStart = () => {
const websocket = new WebSocket(`${protocol}://${host}/webrtc/music?name=${name}`)
websocket.onmessage = async event => {
const data = JSON.parse(event.data) const data = JSON.parse(event.data)
const channels_init = (webrtc) => { const channels_init = (webrtc) => {
return Object.entries(this.channels).map(([name, callback]) => { return Object.entries(this.channels).map(([name, callback]) => {
@ -27,7 +30,7 @@ export default class ClientList {
const webrtc = new RTCPeerConnection() const webrtc = new RTCPeerConnection()
webrtc.onicecandidate = event => { webrtc.onicecandidate = event => {
if (event.candidate) { if (event.candidate) {
this.websocket.send(JSON.stringify({ websocket.send(JSON.stringify({
type: 'candidate', type: 'candidate',
id: data.id, id: data.id,
candidate: event.candidate candidate: event.candidate
@ -56,7 +59,7 @@ export default class ClientList {
const offer = await webrtc.createOffer() const offer = await webrtc.createOffer()
await webrtc.setLocalDescription(offer) await webrtc.setLocalDescription(offer)
this.clientlist.push({ id: data.id, name: data.name, webrtc, channels }) this.clientlist.push({ id: data.id, name: data.name, webrtc, channels })
this.websocket.send(JSON.stringify({ type: 'offer', id: data.id, offer })) websocket.send(JSON.stringify({ type: 'offer', id: data.id, offer }))
this.add(data) this.add(data)
return return
} }
@ -77,7 +80,7 @@ export default class ClientList {
await webrtc.setRemoteDescription(data.offer) await webrtc.setRemoteDescription(data.offer)
const answer = await webrtc.createAnswer() const answer = await webrtc.createAnswer()
await webrtc.setLocalDescription(answer) await webrtc.setLocalDescription(answer)
this.websocket.send(JSON.stringify({ type: 'answer', id: data.id, answer })) websocket.send(JSON.stringify({ type: 'answer', id: data.id, answer }))
return return
} }
if (data.type === 'answer') { if (data.type === 'answer') {
@ -94,6 +97,15 @@ export default class ClientList {
} }
console.log('收到未知数据:', data) console.log('收到未知数据:', data)
} }
websocket.onclose = event => {
console.log('WebSocket 断线重连...')
setTimeout(() => {
this.websocket = linkStart()
}, 1000)
}
return websocket
}
this.websocket = linkStart()
} }
setChannel(name, option) { setChannel(name, option) {
this.channels[name] = option this.channels[name] = option