Explorar o código

小黄车 添加直播间的数据

yuhongqi hai 4 meses
pai
achega
df8847b8e9
Modificáronse 1 ficheiros con 49 adicións e 132 borrados
  1. 49 132
      pages/home/living.vue

+ 49 - 132
pages/home/living.vue

@@ -145,7 +145,7 @@
 									<u-input :placeholder="liveItem.placeholderText" border="none"
 										customStyle='font-size:24rpx;' v-model="liveItem.value" shape='circle'
 										color='#fff' placeholderStyle='color:#e7e7e7' class="ml20"
-										@keydown.enter="sendMsg(liveItem)" @confirm="sendMsg(liveItem)">
+										@keydown.enter="sendMsg(liveItem)">
 									</u-input>
 								</view>
 								<view class="justify-between mr30  align-center">
@@ -294,7 +294,7 @@
 	// var wsUrl = "ws://192.168.10.166:7114/app/webSocket"; //余红奇
 	// var wsUrl = "ws://192.168.10.125:7114/app/webSocket"; //涂小龙
 	var wsUrl = "wss://live.test.ylrztop.com/ws/live-api/app/webSocket"; //余红奇
-	var wsUrl = "ws://192.168.10.166:7114/app/webSocket"; //余红奇
+	// var wsUrl = "ws://192.168.10.166:7114/app/webSocket"; //余红奇
 	// var wsUrl = "ws://192.168.10.125:7114/app/webSocket"; //涂小龙
 	// var wsUrl = "ws://live.test.ylrztop.com/prod-api/app/webSocket"; //余红奇
 	// var wsUrl = "ws://nd383294.natappfree.cc/app/webSocket"; //余红奇
@@ -389,12 +389,14 @@
 
 
 		onLoad(options) {
-			this.userinfo = JSON.parse(uni.getStorageSync("userInfo")) <<
-				// 初始化直播间列表
-				this.initLiveList(options);
+			this.initTime();
 			if (options.liveId) {
 				this.liveId = options.liveId; // 仅当 liveId 变化时更新
 			}
+			this.userinfo = JSON.parse(uni.getStorageSync("userInfo")) 
+				// 初始化直播间列表
+			this.initLiveList(options);
+			
 			const platform = uni.getSystemInfoSync().platform;
 			if (['mp-weixin', 'mp-alipay', 'mp-baidu', 'mp-toutiao'].includes(platform)) {
 				// 确保 API 存在再调用
@@ -415,6 +417,8 @@
 				console.log('当前平台无需显示分享菜单');
 			}
 		},
+		onReady(){
+		},
 		onShareAppMessage() {
 			return {
 				// title: this.product.title,
@@ -439,40 +443,6 @@
 
 			}
 		},
-		mounted() {
-			// this.getLiveMsg() // 获取最近聊天记录
-			// this.onLike()
-			this.getliveViewData() ////直播间点赞、关注、在线人数数据
-
-			// this.intervalId = setInterval(() => {
-			// 	this.getliveViewData();
-			// }, 60 * 1000);
-			// this.getLiveinformation() // 获取直播间信息接口
-			this.getliveOrder() //正在购买
-			// this.getliveStore() // 获取小黄车 店铺展示
-			// this.getliveGoods() // 获取小黄车 商品详情
-			this.getliveUser() // 获取直播间用户
-			this.initTime()
-			// this.initWebSocket()
-			this.initSocket()
-			var that = this;
-			uni.$on('initSocket', () => {
-				that.initSocket()
-			})
-			uni.$on('sendMsg', (item) => {
-				that.sendMsg(item)
-			})
-			uni.$on('closeWebSocket', () => {
-				that.closeWebSocket()
-			})
-			this.getEWechatSdk();
-
-			this.getliving() //hls
-			// this.gettalklist()
-			// this.getAnswerlists()
-
-		},
-
 		onHide() {
 			clearInterval(this.intervalId); // 页面隐藏时清理
 		},
@@ -545,7 +515,7 @@
 				}
 
 				if (this.reconnectTimer) {
-					clearTimeout(this.reconnectTimer);
+					clearInterval(this.reconnectTimer);
 					this.reconnectTimer = null;
 				}
 
@@ -569,11 +539,8 @@
 				const currentLive = this.list[this.currentSwiperIndex];
 				if (!currentLive) return;
 
-				// 确保WebSocket连接已初始化
-				if (!this.socketInstances[currentLive.liveId] || !this.socketInstances[currentLive.liveId].isOpen) {
-					this.initSocket(currentLive);
-				}
 
+				console.log("initCurrentLiveData:" + currentLive)
 				try {
 					// 并行加载,但允许单个失败不阻塞整体
 					await Promise.allSettled([
@@ -598,7 +565,6 @@
 						console.error("直播间列表为空,无法初始化");
 						return;
 					}
-
 					// 设置初始直播间索引
 					if (options.liveId) {
 						const index = this.list.findIndex(item => item.liveId == options.liveId);
@@ -606,14 +572,16 @@
 					} else {
 						this.currentSwiperIndex = 0;
 					}
+					console.log(this.currentSwiperIndex)
 
 					// 获取当前直播间的liveItem
 					const currentLive = this.list[this.currentSwiperIndex];
+					console.log(currentLive)
 					if (currentLive) {
 						this.liveId = currentLive.liveId;
 						// 只初始化当前直播间的WebSocket
-						await this.getLiveMsg(currentLive);
-						await this.initCurrentLiveData();
+						// await this.getLiveMsg(currentLive);
+						// await this.initCurrentLiveData();
 						this.preloadNearbyLives();
 					}
 
@@ -661,6 +629,7 @@
 
 				// 1. 关闭旧直播间连接,暂停视频
 				const oldLive = this.list[oldIndex];
+				console.log("onSwiperChange")
 				if (oldLive) {
 					this.closeWebSocket(oldLive.liveId);
 					this.pauseVideo(oldLive);
@@ -684,6 +653,7 @@
 				try {
 					// 并行加载关键数据(视频、观众、商品等)
 					await Promise.all([
+						this.initSocket(),
 						this.getliving(newLive), // 视频源
 						this.getLiveMsg(newLive), // 聊天记录
 						this.getliveViewData(newLive), // 点赞/关注数据
@@ -789,23 +759,7 @@
 				}
 				this.preloading = false;
 			},
-			// 初始化直播间数据
-			initLiveData() {
-				// 重置数据
-				this.resetLiveData();
-
-				// 初始化直播间特定数据
-				this.getLiveMsg();
-				this.getliveViewData();
-				this.getliveOrder();
-				this.getliving();
-				this.initSocket();
-				// 设置定时器
-				this.intervalId = setInterval(() => {
-					this.getliveViewData();
-				}, 60 * 1000);
-			},
-
+	
 
 			openViews() {
 				// 计算scroll-view高度
@@ -1122,7 +1076,7 @@
 				if (currentLive) {
 					this.pauseVideo(currentLive);
 				}
-
+				
 				// 关闭所有WebSocket连接
 				this.closeWebSocket();
 
@@ -1380,7 +1334,7 @@
 
 				// 清除所有定时器
 				clearInterval(this.pingpangTimes);
-				clearTimeout(this.reconnectTimer);
+				clearInterval(this.reconnectTimer);
 
 				// 关闭指定或所有WebSocket连接
 				if (liveId) {
@@ -1445,17 +1399,19 @@
 					});
 				}, 30000); // 30秒心跳间隔
 			},
-			initSocket(liveItem) {
+			initSocket() {
+				console.log(this.liveId);
 				// 如果没有指定直播间,不初始化
-				if (!liveItem || !liveItem.liveId) return;
+				if ( !this.liveId) return;
 
-				const liveId = liveItem.liveId;
+				const liveId = this.liveId;
 
 				// 检查是否是当前活跃的直播间
 				if (this.currentSwiperIndex !== this.list.findIndex(item => item.liveId === liveId)) {
 					console.log(`不初始化非当前直播间 ${liveId} 的WebSocket`);
 					return;
 				}
+				
 
 				// 关闭之前的连接(如果存在)
 				if (this.socketInstances[liveId]) {
@@ -1469,6 +1425,7 @@
 				}
 
 				this.isManualClose = false;
+				console.log(this.timestamp)
 
 				// 生成签名
 				const signature = CryptoJS.HmacSHA256(
@@ -1486,71 +1443,35 @@
 					const socketTask = uni.connectSocket({
 						url: `${wsUrl}?userId=${this.userinfo.userId}&liveId=${liveId}&userType=${this.userType}&timestamp=${this.timestamp}&signature=${signature}`,
 						success: () => {
-							this.socketInstances[liveId].instance = socketTask;
-							this.setupSocketListeners(liveId);
+							console.log('WebSocket API 调用成功,正在建立连接...');
 						},
 						fail: (err) => {
 							console.error('WebSocket 连接失败:', err);
 							this.scheduleReconnect(liveId);
 						}
 					});
+					socketTask.onOpen((res) => {
+						console.log('WebSocket 连接已成功建立', res);
+						this.socketInstances[liveId].instance = socketTask;
+						this.socketInstances[liveId].isOpen = true;
+					})
+					socketTask.onMessage((res)=>{
+						// 找到对应的直播间并更新数据
+						const targetLive = this.list.find(item => item.liveId === liveId);
+						this.handleSocketMessage(res, targetLive)
+					})
 				} catch (e) {
 					console.error('创建 WebSocket 异常:', e);
 					this.scheduleReconnect(liveId);
 				}
 			},
-			// 设置 WebSocket 监听器
-			setupSocketListeners(liveId) {
-				const socketItem = this.socketInstances[liveId];
-				if (!socketItem || !socketItem.instance) return;
-
-				const socketInstance = socketItem.instance;
-
-				socketInstance.onOpen(() => {
-					socketItem.isOpen = true; // 更新为当前实例的打开状态
-					this.reconnectCount = 0;
-					console.log(`直播间 ${liveId} WebSocket 连接成功`);
-					this.startHeartbeat(liveId);
-				});
-
-				socketInstance.onClose(() => {
-					socketItem.isOpen = false; // 更新为当前实例的关闭状态
-					console.log(`直播间 ${liveId} WebSocket 连接关闭`);
-					if (!this.isManualClose) {
-						this.scheduleReconnect(liveId);
-					}
-				});
-				socketInstance.onMessage((res) => {
-					try {
-						const redata = JSON.parse(res.data);
-						// 找到对应的直播间并更新数据
-						const targetLive = this.list.find(item => item.liveId === liveId);
-						if (targetLive) {
-							targetLive.talklist.push(redata.data);
-							this.$nextTick(() => {
-								targetLive.scrollIntoView =
-									`list_${targetLive.talklist.length - 1}`;
-							});
-							if (redata.data.cmd == 'sendMsg') {
-								this.talklist.push(redata.data);
-								this.$nextTick(() => {
-									this.scrollIntoView =
-										`list_${this.talklist.length - 1}`; // 最后一项的id
-								});
-							} else if (redata.data.cmd == 'deleteId') {
-								uni.$emit('deleteId');
-							}
-							// 处理各种消息类型
-							this.handleSocketMessage(redata.data, targetLive);
-						}
-					} catch (e) {
-						console.error('解析消息失败:', e);
-					}
-				});
-			},
 			// 处理Socket消息
 			handleSocketMessage(message, liveItem) {
-				if (message.cmd == 'red') {
+				console.log("开始监听处理消息")
+				if(message.cmd == 'sendMsg'){
+					
+				}
+				else if (message.cmd == 'red') {
 					// 领红包
 					liveItem.redInfo = JSON.parse(message.data);
 				} else if (message.cmd == 'sendRedPacketQuestion') {
@@ -1561,14 +1482,14 @@
 					setTimeout(() => {
 						liveItem.showWelcomeMessage = false;
 					}, 1000);
-				} else if (redata.data.cmd == 'live_start') {
+				} else if (message.cmd == 'live_start') {
 					// 直播开始
-				} else if (redata.data.cmd == 'live_end') {
+				} else if (message.cmd == 'live_end') {
 					// 直播结束
-				} else if (redata.data.cmd == 'deleteId') {
+				} else if (message.cmd == 'deleteId') {
 					uni.$emit('deleteId');
-				} else if (redata.data.cmd == 'sendRedPacketQuestion') {
-					const list = JSON.parse(redata.data.data)
+				} else if (message.cmd == 'sendRedPacketQuestion') {
+					const list = JSON.parse(message.data)
 					liveItem.redanswerAll = [...liveItem.redanswerAll, ...list]
 					if (liveItem.redanswerAll[1].randomAmount !== null) {
 						liveItem.redanswertips = JSON.parse(liveItem.redanswerAll[0]
@@ -1585,11 +1506,12 @@
 
 				console.log(`将在 ${delay}ms 后重连 (尝试 ${this.reconnectCount}/${this.maxReconnectAttempts})`);
 
-				this.reconnectTimer = setTimeout(() => {
+				this.reconnectTimer = setInterval(() => {
 					this.initSocket();
 				}, delay);
 			},
 			sendMsg(liveItem) {
+				console.log("sendMsg")
 				if (!liveItem || !liveItem.liveId) return;
 
 				const liveId = liveItem.liveId;
@@ -1605,11 +1527,6 @@
 						title: "连接未建立,正在重试...",
 						icon: 'none'
 					});
-
-					// 3秒后重试发送
-					setTimeout(() => {
-						this.sendMsg(liveItem);
-					}, 3000);
 					return;
 				}