Browse Source

实时通信

zhangbs 2 years ago
parent
commit
2e26e4d437
3 changed files with 9 additions and 25 deletions
  1. 0 18
      pages/index/index.vue
  2. 0 7
      pages/message/index.vue
  3. 9 0
      store/websocketStore.js

+ 0 - 18
pages/index/index.vue

@@ -18,26 +18,8 @@
 		onLoad: async function() {
 			const that = this;
 			await that.searchConfig();
-			await that.watchlogin();
 		},
 		methods: {
-			watchlogin() {
-				const that = this;
-				if (that.$store.state.socketTask == null) {
-					uni.getStorage({
-						key: 'token',
-						success: function(res) {
-							let user = that.$jwt(res.data);
-							if (user._id) {
-								//当websocket收到后端发送的消息时,触发
-								let config = that.$config.wsUrl;
-								// 开启websocket
-								that.$store.dispatch('websocketInit', config + `/${user._id}`);
-							}
-						}
-					})
-				}
-			},
 			// 查询基本设置
 			async searchConfig() {
 				const that = this;

+ 0 - 7
pages/message/index.vue

@@ -83,13 +83,6 @@
 						if (user) {
 							that.$set(that, `user`, user)
 							that.search();
-							if (that.$store.state.socketTask == null) {
-								//当websocket收到后端发送的消息时,触发
-								let config = that.$config.wsUrl;
-								// 开启websocket
-								that.$store.dispatch('websocketInit', config +
-									`/${user._id}`);
-							}
 						}
 					}
 				})

+ 9 - 0
store/websocketStore.js

@@ -30,6 +30,15 @@ const store = new Vuex.Store({
 			state.socketTask.onMessage(res => dispatch('websocketOnMessage', res))
 			state.socketTask.onClose(res => {
 				state.socketTask == null
+				state.socketTask = uni.connectSocket({
+					url, // url是websocket连接ip
+					success: () => {
+						console.log('WebSocket连接成功!')
+					},
+					fail: e => {
+						console.log('连接失败' + e)
+					}
+				})
 				console.log('WebSocket连接关闭')
 			});
 			state.socketTask.onError(res => {