Selaa lähdekoodia

销售直播代码 直播间 根据liveId保存连接

yuhongqi 3 viikkoa sitten
vanhempi
commit
47f657f229
2 muutettua tiedostoa jossa 36 lisäystä ja 7 poistoa
  1. 30 6
      src/store/index.js
  2. 6 1
      src/views/live/liveConsole/index.vue

+ 30 - 6
src/store/index.js

@@ -20,17 +20,41 @@ const store = new Vuex.Store({
   },
   getters,
   state: {
-    liveWs: null
+    liveWs: {}
   },
   mutations: {
-    setLiveWs(state, ws) {
-      state.liveWs = ws
+    // 更新为支持多个 WebSocket 连接
+    setLiveWs(state, { ws, liveId }) {
+      // 使用 liveId 作为键来存储不同的 WebSocket 连接
+      Vue.set(state.liveWs, liveId, ws);
     },
+    // 添加移除 WebSocket 连接的 mutation
+    removeLiveWs(state, liveId) {
+      Vue.delete(state.liveWs, liveId);
+    }
   },
   actions: {
-    initLiveWs({ commit }, { liveWsUrl, liveId, userId }) {
-      const ws = new LiveWS(liveWsUrl, liveId, userId)
-      commit('setLiveWs', ws)
+    // 修改 action 以正确传递参数
+    initLiveWs({ commit, state }, { liveWsUrl, liveId, userId }) {
+      // 如果已经存在对应 liveId 的连接,先关闭它
+      if (state.liveWs[liveId]) {
+        state.liveWs[liveId].close();
+      }
+
+      // 创建新的 WebSocket 连接
+      const ws = new LiveWS(liveWsUrl, liveId, userId);
+
+      // 提交到 mutation
+      commit('setLiveWs', { ws, liveId });
+
+      return ws;
+    },
+    // 添加关闭特定 WebSocket 连接的 action
+    closeLiveWs({ commit, state }, liveId) {
+      if (state.liveWs[liveId]) {
+        state.liveWs[liveId].close();
+        commit('removeLiveWs', liveId);
+      }
     }
   }
 })

+ 6 - 1
src/views/live/liveConsole/index.vue

@@ -601,7 +601,7 @@ export default {
         liveId: this.liveId,
         userId: this.userId
       })
-      this.socket = this.$store.state.liveWs
+      this.socket = this.$store.state.liveWs[this.liveId]
       this.socket.onmessage = (event) => this.handleWsMessage(event)
     },
     handleWsMessage(event) {
@@ -661,6 +661,11 @@ export default {
   destroyed() {
     this.socket?.close()
     this.hls?.destroy();
+    this.$store.dispatch('closeLiveWs', {
+      liveWsUrl: this.liveWsUrl,
+      liveId: this.liveId,
+      userId: this.userId
+    })
   }
 }
 </script>