Browse Source

消息通信

chenjj 3 months ago
parent
commit
5fbab419aa
7 changed files with 47 additions and 49 deletions
  1. 13 12
      App.vue
  2. 2 2
      config.js
  3. 1 1
      main.js
  4. 4 0
      pages/mine/index.vue
  5. 6 20
      store/modules/user.ts
  6. 8 2
      utils/WebSocketManager.js
  7. 13 12
      utils/soketMixin.js

+ 13 - 12
App.vue

@@ -3,24 +3,25 @@
 import { watch } from 'vue';
 import store from '@/store'
 import { onLaunch, onShow, onHide } from "@dcloudio/uni-app";
+import soketMixin from '@/utils/soketMixin'
 export default {
 	data: {
 		userId: uni.getStorageSync('userId') //读取本地存储
 	},
+	mixins: [soketMixin],
 	onLaunch: function () {
 		//develop:开发版 trial:体验版  release:正式版
-		// console.log('App Launch',uni.getAccountInfoSync().miniProgram.envVersion)
-		uni.loadFontFace({
-			family: "uicon-iconfont",
-			source: 'url("https://at.alicdn.com/t/font_2225171_8kdcwk4po24.ttf")',
-			global: true,
-			success: (success) => {
-				console.log("Font loaded successfully", success);
-			},
-			fail: (fail) => {
-				console.log("Font loading failed", fail);
-			},
-		});
+		// uni.loadFontFace({
+		// 	family: "uicon-iconfont",
+		// 	source: 'url("https://at.alicdn.com/t/font_2225171_8kdcwk4po24.ttf")',
+		// 	global: true,
+		// 	success: (success) => {
+		// 		console.log("Font loaded successfully", success);
+		// 	},
+		// 	fail: (fail) => {
+		// 		console.log("Font loading failed", fail);
+		// 	},
+		// });
 	},
 	// onShow: function () {
 	// 	//设置默认角色

+ 2 - 2
config.js

@@ -1,7 +1,7 @@
 const base_url = {
-  // develop:'http://192.168.100.128:9527',//开发版 
+  develop:'http://192.168.100.128:9527',//开发版 
   // develop: 'http://192.168.100.139:9527', //嵘哥
-  develop: 'https://yongc.top/prod-api',//体验版
+  // develop: 'https://yongc.top/prod-api',//体验版
   // develop: 'https://goldshulin.com/prod-api',//体验版
 
   trial: 'https://yongc.top/prod-api',//体验版

+ 1 - 1
main.js

@@ -12,7 +12,7 @@ export function createApp() {
   app.use(plugins)
   app.use(store)
   app.mixin(shareMixin)
-  app.mixin(soketMixin)
+  // app.mixin(soketMixin)
 
   return {
     app

+ 4 - 0
pages/mine/index.vue

@@ -297,10 +297,12 @@ const userList = [
 const switchUserType = (userType) => {
   uni.setStorageSync('userType', userType)
   store.dispatch('GetInfo').then((res) => {
+    uni.$u.closeSoket();
     userInfo.value = store.state.user
     userOrWorker({ userType: userType })
       .then(res => {
         console.log("TCL: loginSuccess -> res", res)
+        uni.$u.connectSoket(userInfo.value.userId)
         uni.reLaunch({
           url: '/pages/index',
         })
@@ -385,6 +387,8 @@ const getDetails = async () => {
 }
 
 const handLsetTing = () => {
+  console.log('uni.$u.closeSoket',uni.$u);
+
   uni.navigateTo({
     url: '/pages_mine/pages/setupUser/index',
   })

+ 6 - 20
store/modules/user.ts

@@ -5,7 +5,6 @@ import { login, logout, getInfo } from '@/api/login'
 import { getToken, setToken, removeToken } from '@/utils/auth'
 import { UserState, UserForm } from '@/types/store'
 import { Module } from 'vuex'
-import WebSocketManager from '@/utils/WebSocketManager.js';
 const baseUrl = config.baseUrl
 
 const user: Module<UserState, UserState> = {
@@ -99,6 +98,7 @@ const user: Module<UserState, UserState> = {
         login(username, password, code, uuid, referrerType, referrerId, latitude, longitude).then((res: any) => {
           setToken(res.token)
           commit('SET_TOKEN', res.token)
+          
           resolve(res)
         }).catch(error => {
           reject(error)
@@ -131,26 +131,9 @@ const user: Module<UserState, UserState> = {
           commit('SET_NICKNAME', res.user.nickName)
           commit('SET_USERID', res.user.userId)
 
+          uni.setStorageSync('userType', res.user.userId)
 
-
-          // if (this.wsManager) {
-          //   this.wsManager.closeConnection();
-          // } else {
-          //   //获取账户时,连接soket 
-          //   const ms = new WebSocketManager(res.user.userId);
-          //   // 设置消息回调
-          //   ms.onMessage(data => {
-          //     console.log("处理消息逻辑", data.data)
-          //     // 处理消息逻辑
-          //     if (data.type === 'msgUnreadCount') {
-          //       commit('SET_MESSAGECOUNT', data.data);
-          //     }
-          //   });
-          //   // 建立连接
-          //   ms.connect();
-          //   commit('SET_MESSAGE', ms)
-
-          // }
+          uni.$u.connectSoket(res.user.userId);
 
 
           resolve(res)
@@ -169,6 +152,8 @@ const user: Module<UserState, UserState> = {
           commit('SET_PERMISSIONS', [])
           removeToken()
 
+          //清除soket
+          uni.$u.closeSoket();
           uni.setStorageSync('userType', 1)
           // uni.setStorageSync('userId', null)
           uni.removeStorageSync('userId')
@@ -197,6 +182,7 @@ const user: Module<UserState, UserState> = {
         commit('SET_ROLES', [])
         commit('SET_PERMISSIONS', [])
         removeToken()
+        uni.$u.closeSoket();
         uni.removeStorageSync('userId')
         storage.clean()
       })

+ 8 - 2
utils/WebSocketManager.js

@@ -34,11 +34,14 @@ class WebSocketManager {
             console.log('已存在连接,正在关闭旧连接...');
             this.socketTask.close();
         }
+        //重新创建链接后、重连次数重置
+        this.connectCount = 0;//重连次数
+
         this.isConnecting = true;
         console.log('建立 WebSocket 连接:', this.url);
         this.socketTask = uni.connectSocket({
             url: this.url,
-            success: () => console.log('WebSocket 连接创建成功'),
+            success: (res) => console.log('WebSocket 连接创建成功',res),
             header: { 
                 'Authorization': `Bearer ${getToken()}` 
             }, 
@@ -76,7 +79,7 @@ class WebSocketManager {
 
         this.socketTask.onError(err => {
             console.error('WebSocket 发生错误:', err);
-   
+            this.connectCount <= 3 && this.reconnect();
         });
 
         this.socketTask.onClose(() => {
@@ -144,10 +147,13 @@ class WebSocketManager {
      * 主动关闭连接
      */
     closeConnection() {
+        this.connectCount  = 3; //手动关闭不做重新连接
         console.log('主动关闭连接',this.socketTask);
+        uni.closeSocket(this.socketTask);
         this.socketTask.close();
         this.socketTask = null;
         this.stopHeartbeat();
+        store.dispatch('handleSoket', null)
     }
 
     /**

+ 13 - 12
utils/soketMixin.js

@@ -10,26 +10,21 @@ export default {
   },
   onShow: function () {
     console.log('App-Show^^')
+    uni.$u.connectSoket = this.connectSoket;
+    uni.$u.closeSoket = this.closeSoket;
+
     uni.$u.debounce(this.connectSoket(), 500)
   },
   onHide: function () {
     console.log('App-Hide^^')
     this.closeSoket();
   },
-  onLaunch:function () { 
-    console.log('App-onLaunch^^')
-    uni.$u.debounce(this.connectSoket(), 500)
-  },
-  onExit: function () { 
-    console.log('App onExit^^')
-  },
-
   methods: {
-    connectSoket(){
+    connectSoket(user_id){
         const ws = store.state.user.wsManager;
-        const userId = uni.getStorageSync('userId');
+        const userId = user_id || uni.getStorageSync('userId');
         const token = getToken();
-        // console.log('connectSoket------------>',!ws , userId,!ws && userId);
+        console.log('connectSoket------------>');
 
           if (!ws && userId && token) {
             console.log('connectSoket-----+++------->',!ws , userId,!ws && userId);
@@ -49,7 +44,13 @@ export default {
           }
     },
     closeSoket(){
-        console.log('closeSoket',store);
+    
+        const ws = store.state.user.wsManager;
+        console.log('closeSoket------>ws',ws);
+        if(ws){
+          ws.closeConnection();
+        }
+        
     }
   }
 }