ZaiZai 2 years ago
parent
commit
b89d5e25e9
3 changed files with 83 additions and 65 deletions
  1. 5 64
      App.vue
  2. 70 0
      httpApi/request/socket.js
  3. 8 1
      pages/index/index.vue

+ 5 - 64
App.vue

@@ -2,9 +2,10 @@
     import {useAppStore} from "@/store";
     import website from "@/config/index";
     import userApi from '~api/user/index';
-    import {getStorage, setStorage, delStorage} from "@/utils/storage";
-    import {calcDate, getObjValue, isNullES, isString} from "js-fast-way";
-    import {getWssApiUrl} from "@/config/envApi";
+    import {getStorage, setStorage} from "@/utils/storage";
+    import {calcDate, getObjValue, isNullES} from "js-fast-way";
+    import HcSocket from "@/httpApi/request/socket";
+
 	export default {
         data() {
             return {
@@ -12,7 +13,7 @@
             }
         },
 		onLaunch() {
-            this.setInitSocket()
+            HcSocket.initSocket()
 		},
 		onShow() {
 			//console.log('App Show')
@@ -67,66 +68,6 @@
                     return Promise.reject(res)
                 }
             },
-            //长连接
-            setInitSocket() {
-                this.timeId = setInterval(() => {
-                    if (this.isSocket) {
-                        clearInterval(this.timeId)
-                    } else {
-                        this.setAppSocket()
-                    }
-                    console.log('setInterval')
-                }, 3000)
-            },
-            setAppSocket() {
-                const {user_id} = this.userInfo
-                if (user_id) {
-                    this.initWebSocket(user_id)
-                }
-            },
-            initWebSocket(user_id) {
-                const _this = this, store = useAppStore()
-                let startTime = 0;
-                uni.connectSocket({
-                    url: getWssApiUrl() + user_id,
-                    complete: ()=> {
-                        startTime = new Date()
-                        _this.isSocket = true
-                        console.log('websocket链接成功')
-                    }
-                });
-                uni.onSocketOpen((res) => {
-                    console.log('WebSocket连接已打开!');
-                    _this.sendSocketMessage();
-                });
-                uni.onSocketError((res) => {
-                    console.log('WebSocket连接失败,请检查!');
-                });
-                uni.onSocketClose((res) => {
-                    console.log('WebSocket 已关闭!');
-                    //关闭后在连接
-                    const endTime = new Date()
-                    const duration = endTime - startTime
-                    if(duration > 1000) {
-                        _this.isSocket = false
-                        //_this.setAppSocket()
-                    }
-                });
-                //收到的消息
-                uni.onSocketMessage(({data}) => {
-                    const countData = isString(data) ? JSON.parse(data) : {}
-                    if (!isNullES(countData)) {
-                        console.log(countData)
-                        store.setMsgCountData(countData)
-                    }
-                });
-            },
-            sendSocketMessage() {
-                const store = useAppStore()
-                uni.sendSocketMessage({
-                    data: store.projectId + ',' + store.contractId
-                });
-            },
         }
 	}
 </script>

+ 70 - 0
httpApi/request/socket.js

@@ -0,0 +1,70 @@
+import {getWssApiUrl} from "@/config/envApi";
+import {getStorage} from "@/utils/storage";
+import {getObjVal, getObjValue, isString} from "js-fast-way";
+import {useAppStore} from "@/store";
+
+export default class HcSocket {
+    static socketTask = null
+    static timeID = null
+    static isConnect = false
+
+    static initSocket() {
+        let _this = this;
+        this.timeID = setInterval(() => {
+            if (!_this.isConnect) {
+                const { user_id } = getObjValue(getStorage('userInfo'))
+                if (!user_id) return false;
+                _this.connectSocket(user_id)
+            } else {
+                clearInterval(_this.timeID)
+            }
+        }, 3000)
+    }
+
+    static connectSocket(user_id) {
+        const _this = this, store = useAppStore();
+        this.socketTask = uni.connectSocket({
+            url: getWssApiUrl() + user_id,
+            success: ()=> {
+                console.log('socket 连接成功')
+            },
+            fail: () => {
+                console.log('socket 连接失败')
+            }
+        });
+        //连接已打开
+        this.socketTask.onOpen(function(res) {
+            console.log('socket 连接已打开');
+            _this.isConnect = true
+            const projectId = getStorage('projectId')
+            const contractId = getStorage('contractId')
+            _this.sendSocketMsg(`${projectId},${contractId}`)
+        })
+        //连接失败
+        this.socketTask.onError(function(res) {
+            console.log('socket 连接打开失败,请检查!');
+            //进入重新连接
+            setTimeout(() => {
+                _this.connectSocket();
+            }, 3000)
+        })
+        //监听连接关闭
+        this.socketTask.onClose((e) => {
+            console.log('socket 连接关闭!');
+        })
+        //收到的消息
+        this.socketTask.onMessage(function({data}) {
+            const countData = isString(data) ? JSON.parse(data) : {}
+            if (getObjVal(countData)) {
+                console.log('收到服务器内容:', countData);
+                store.setMsgCountData(countData)
+            }
+        });
+        return this.socketTask
+    }
+
+    //发送消息
+    static sendSocketMsg(msg) {
+        this.socketTask.send({data: msg});
+    }
+}

+ 8 - 1
pages/index/index.vue

@@ -208,7 +208,7 @@
 </template>
 
 <script setup>
-import {ref} from "vue";
+import {ref, watch} from "vue";
 import {useAppStore} from "@/store";
 import {onShow, onHide} from '@dcloudio/uni-app'
 import mainApi from '~api/user/index';
@@ -234,6 +234,13 @@ onHide(() => {
     isAnimation.value = false
 })
 
+//深度监听长连接消息
+watch(() => [
+    store.msgCountData,
+], ([val]) => {
+    msgCountData.value = val
+}, {deep: true,})
+
 //获取配置
 const appCheck = ref(1)
 const userConfigInfo = async () => {