ソースを参照

fix: 优化代码

shuisheng 2 年 前
コミット
db03f7c6b5
5 ファイル変更60 行追加84 行削除
  1. 0 5
      src/hooks/use-pull.ts
  2. 43 59
      src/hooks/use-push.ts
  3. 0 1
      src/network/webRtc.ts
  4. 13 8
      src/network/webSocket.ts
  5. 4 11
      src/views/push/index.vue

+ 0 - 5
src/hooks/use-pull.ts

@@ -269,13 +269,9 @@ export function usePull({
 
   async function batchSendOffer(socketId: string) {
     await nextTick(async () => {
-      console.log('batchSendOffer', offerSended.value, liveUserList.value);
-      console.log(socketId, 2222222);
       if (!offerSended.value.has(socketId) && socketId !== getSocketId()) {
-        console.log('kkkkkk', socketId);
         hooksRtcMap.value.add(await startNewWebRtc({ receiver: socketId }));
         await addTransceiver(socketId);
-        console.warn('new WebRTCClass完成');
         console.log('执行sendOffer', {
           sender: getSocketId(),
           receiver: socketId,
@@ -302,7 +298,6 @@ export function usePull({
             })
           );
           await addTransceiver(item.socketId);
-          console.warn('new WebRTCClass完成');
           console.log('执行sendOffer', {
             sender: getSocketId(),
             receiver: item.socketId,

+ 43 - 59
src/hooks/use-push.ts

@@ -61,12 +61,6 @@ export function usePush({
   const disabled = ref(false);
   const localStream = ref();
   const offerSended = ref(new Set());
-  const hooksRtcMap = ref(new Set());
-  const sidebarList = ref<
-    {
-      socketId: string;
-    }[]
-  >([]);
 
   const track = reactive({
     audio: true,
@@ -109,6 +103,40 @@ export function usePush({
     txt: string;
   }>();
 
+  watch(
+    () => userStore.userInfo,
+    async (newVal) => {
+      if (newVal) {
+        const res = await userHasLiveRoom();
+        if (!res) {
+          await useTip('你还没有直播间,是否立即开通?');
+          await handleCreateUserLiveRoom();
+        }
+      }
+    }
+  );
+
+  onMounted(() => {
+    if (!loginTip()) return;
+  });
+
+  onUnmounted(() => {
+    clearInterval(heartbeatTimer.value);
+    closeWs();
+    closeRtc();
+  });
+
+  function closeWs() {
+    const instance = networkStore.wsMap.get(roomId.value);
+    instance?.close();
+  }
+
+  function closeRtc() {
+    networkStore.rtcMap.forEach((rtc) => {
+      rtc.close();
+    });
+  }
+
   async function userHasLiveRoom() {
     const res = await fetchUserHasLiveRoom(userStore.userInfo?.id!);
     if (res.code === 200 && res.data) {
@@ -132,27 +160,6 @@ export function usePush({
     }
   }
 
-  watch(
-    () => userStore.userInfo,
-    async (newVal) => {
-      if (newVal) {
-        const res = await userHasLiveRoom();
-        if (!res) {
-          await useTip('你还没有直播间,是否立即开通?');
-          await handleCreateUserLiveRoom();
-        }
-      }
-    }
-  );
-
-  onMounted(() => {
-    if (!loginTip()) return;
-  });
-
-  onUnmounted(() => {
-    clearInterval(heartbeatTimer.value);
-  });
-
   async function startLive() {
     if (!loginTip()) return;
     const flag = await userHasLiveRoom();
@@ -258,17 +265,6 @@ export function usePush({
     }, 1000 * 5);
   }
 
-  function closeWs() {
-    const instance = networkStore.wsMap.get(roomId.value);
-    instance?.close();
-  }
-
-  function closeRtc() {
-    networkStore.rtcMap.forEach((rtc) => {
-      rtc.close();
-    });
-  }
-
   function addTrack() {
     if (!localStream.value) return;
     liveUserList.value.forEach((item) => {
@@ -329,11 +325,7 @@ export function usePush({
         !offerSended.value.has(item.socketId) &&
         item.socketId !== getSocketId()
       ) {
-        hooksRtcMap.value.add(
-          await startNewWebRtc({ receiver: item.socketId })
-        );
         await addTrack();
-        console.warn('new WebRTCClass完成');
         console.log('执行sendOffer', {
           sender: getSocketId(),
           receiver: item.socketId,
@@ -379,13 +371,7 @@ export function usePush({
       if (!instance) return;
       if (data.data.receiver === getSocketId()) {
         console.log('收到offer,这个offer是发给我的');
-        sidebarList.value.push({ socketId: data.data.sender });
         nextTick(async () => {
-          console.log(
-            remoteVideoRef.value[data.data.sender],
-            remoteVideoRef.value,
-            22222
-          );
           const rtc = await startNewWebRtc({
             receiver: data.data.sender,
             videoEl: remoteVideoRef.value[data.data.sender],
@@ -630,18 +616,20 @@ export function usePush({
   /** 结束直播 */
   function endLive() {
     disabled.value = false;
-    closeRtc();
     currMediaTypeList.value = [];
     localStream.value = null;
     localVideoRef.value!.srcObject = null;
+    clearInterval(heartbeatTimer.value);
     const instance = networkStore.wsMap.get(roomId.value);
-    if (!instance) return;
-    instance.send({
-      msgType: WsMsgTypeEnum.roomNoLive,
-      data: {},
-    });
+    if (instance) {
+      instance.send({
+        msgType: WsMsgTypeEnum.roomNoLive,
+        data: {},
+      });
+    }
     setTimeout(() => {
-      instance.close();
+      closeWs();
+      closeRtc();
     }, 500);
   }
   async function getAllMediaDevices() {
@@ -690,8 +678,6 @@ export function usePush({
     startGetUserMedia,
     startLive,
     endLive,
-    closeWs,
-    closeRtc,
     sendDanmu,
     keydownDanmu,
     disabled,
@@ -700,7 +686,5 @@ export function usePush({
     damuList,
     liveUserList,
     currMediaTypeList,
-    hooksRtcMap,
-    sidebarList,
   };
 }

+ 0 - 1
src/network/webRtc.ts

@@ -491,7 +491,6 @@ export class WebRTCClass {
         this.update();
         console.log('准备发送candidate', event.candidate.candidate);
         const roomId = this.roomId.split('___')[0];
-        console.log(this.roomId, networkStore.wsMap.get(roomId)?.socketIo?.id);
         const receiver = this.roomId.split('___')[1];
         const data = {
           candidate: event.candidate.candidate,

+ 13 - 8
src/network/webSocket.ts

@@ -1,6 +1,7 @@
 import { Socket, io } from 'socket.io-client';
 
 import { useNetworkStore } from '@/store/network';
+import { useUserStore } from '@/store/user';
 
 // websocket连接状态
 export enum WsConnectStatusEnum {
@@ -61,20 +62,21 @@ export class WebSocketClass {
   socketIo: Socket | null = null;
   status: WsConnectStatusEnum = WsConnectStatusEnum.disconnect;
   url = '';
-
   roomId = '-1';
   isAdmin = false;
 
-  constructor({ roomId, url, isAdmin }) {
+  constructor(data: { roomId: string; url: string; isAdmin: boolean }) {
     if (!window.WebSocket) {
       alert('当前环境不支持WebSocket!');
       return;
     }
-    this.roomId = roomId;
-    this.isAdmin = isAdmin;
-
-    this.url = url;
-    this.socketIo = io(url, { transports: ['websocket'], forceBase64: false });
+    this.roomId = data.roomId;
+    this.isAdmin = data.isAdmin;
+    this.url = data.url;
+    this.socketIo = io(data.url, {
+      transports: ['websocket'],
+      forceBase64: false,
+    });
     this.update();
   }
 
@@ -89,11 +91,14 @@ export class WebSocketClass {
       return;
     }
     console.warn('【websocket】发送消息', msgType, data);
+    const userStore = useUserStore();
     this.socketIo?.emit(msgType, {
       roomId: this.roomId,
       socketId: this.socketIo.id,
-      data,
       isAdmin: this.isAdmin,
+      user_id: userStore.userInfo?.id,
+      user_token: userStore.token,
+      data,
     });
   };
 

+ 4 - 11
src/views/push/index.vue

@@ -51,7 +51,9 @@
         <div class="sidebar">
           <div class="title">在线人员</div>
           <div
-            v-for="(item, index) in sidebarList"
+            v-for="(item, index) in liveUserList.filter(
+              (item) => item.socketId !== getSocketId()
+            )"
             :key="index"
             class="item"
           >
@@ -193,7 +195,7 @@
 </template>
 
 <script lang="ts" setup>
-import { onMounted, onUnmounted, ref } from 'vue';
+import { onMounted, ref } from 'vue';
 import { useRoute } from 'vue-router';
 
 import { usePush } from '@/hooks/use-push';
@@ -204,7 +206,6 @@ const route = useRoute();
 const userStore = useUserStore();
 
 const liveType = route.query.liveType;
-
 const topRef = ref<HTMLDivElement>();
 const bottomRef = ref<HTMLDivElement>();
 const containerRef = ref<HTMLDivElement>();
@@ -219,8 +220,6 @@ const {
   startGetUserMedia,
   startLive,
   endLive,
-  closeWs,
-  closeRtc,
   sendDanmu,
   keydownDanmu,
   disabled,
@@ -229,18 +228,12 @@ const {
   damuList,
   liveUserList,
   currMediaTypeList,
-  sidebarList,
 } = usePush({
   localVideoRef,
   remoteVideoRef,
   isSRS: liveType === liveTypeEnum.srsPush,
 });
 
-onUnmounted(() => {
-  closeWs();
-  closeRtc();
-});
-
 onMounted(() => {
   if (topRef.value && bottomRef.value && containerRef.value) {
     const res =