diff --git a/src/index.js b/src/index.js index 013ff45..5d71285 100644 --- a/src/index.js +++ b/src/index.js @@ -65,8 +65,8 @@ class WebRTCChat { console.log('WebRTC 聊天应用初始化完成'); - this.initializeElements(); this.initializeSocket(); + this.initializeElements(); this.loadVideoMapping(); this.loadVideoList(); @@ -75,12 +75,12 @@ class WebRTCChat { this.bindEvents(); // 在初始化完成后预加载常用视频 - setTimeout(() => { - this.logMessage('开始预加载常用视频...', 'info'); - this.preloadCommonVideos().catch(error => { - this.logMessage(`预加载过程出错: ${error.message}`, 'error'); - }); - }, 500); + // setTimeout(() => { + // this.logMessage('开始预加载常用视频...', 'info'); + // this.preloadCommonVideos().catch(error => { + // this.logMessage(`预加载过程出错: ${error.message}`, 'error'); + // }); + // }, 500); // 预创建重要视频流 setTimeout(() => { @@ -427,7 +427,7 @@ class WebRTCChat { async precreateImportantVideos() { if (this.isInitialized) return; - this.logMessage('开始预创建重要视频流...', 'info'); + console.log('开始预创建重要流...', 'info'); for (const videoFile of [this.interactionVideo, this.defaultVideo]) { try { @@ -438,13 +438,14 @@ class WebRTCChat { this.logMessage(`预创建视频流失败: ${videoFile} - ${error.message}`, 'error'); } } - - this.isInitialized = true; // 启用开始通话按钮 if (this.startButton) { this.startButton.disabled = false; this.startButton.style.opacity = '1'; } + + this.isInitialized = true; + this.logMessage('重要视频流预创建完成', 'success'); } @@ -1158,6 +1159,7 @@ class WebRTCChat { await this.startVoiceRecording(); this.startButton.disabled = true; + this.startButton.style.opacity = '0.5' this.stopButton.disabled = false; // 显示结束通话按钮 @@ -1182,7 +1184,7 @@ class WebRTCChat { this.socket.emit('call-started'); // 开始播放当前场景的默认视频 - await this.precreateImportantVideos(); + // await this.precreateImportantVideos(); // 隐藏等待连接提示 this.hideConnectionWaiting(); @@ -1242,9 +1244,9 @@ class WebRTCChat { } // 显示开始通话按钮 - this.startButton.disabled = false; + this.startButton.disabled = true; this.startButton.style.display = 'block'; - this.startButton.style.opacity = '1'; + this.startButton.style.opacity = '0.5'; // 移除页面刷新,保持websocket连接 // setTimeout(() => { @@ -1273,16 +1275,36 @@ class WebRTCChat { // 发送用户关闭连接事件到后端 if (this.socket && this.socket.connected) { this.socket.emit('user-disconnect'); + + // 等待服务器确认断开后再刷新 + this.socket.on('disconnect', () => { + console.log('WebSocket已断开,准备刷新页面...'); + setTimeout(() => { + window.location.reload(); + }, 500); + }); + + // 主动断开连接 + setTimeout(() => { + this.socket.disconnect(); + }, 200); + + // 兜底机制:如果2秒内没有正常断开,强制刷新 + setTimeout(() => { + if (this.socket && this.socket.connected) { + console.log('WebSocket断开超时,强制刷新页面'); + window.location.reload(); + } + }, 2000); + } else { + // 如果socket已经断开,直接刷新 + setTimeout(() => { + window.location.reload(); + }, 100); } // 调用停止通话 this.stopCall(); - - // 延迟刷新,确保服务器处理完断开逻辑 - console.log('用户主动断开,300ms后刷新页面清除缓存...'); - setTimeout(() => { - window.location.reload(); - }, 100); } // 清除视频缓存的方法