Bladeren bron

修改socket

ck110 2 weken geleden
bovenliggende
commit
3ac0032484
5 gewijzigde bestanden met toevoegingen van 198 en 98 verwijderingen
  1. 4 1
      App.vue
  2. 127 52
      common/websocketUtil.js
  3. 1 1
      pages/chat/components/message.vue
  4. 63 44
      pages/chat/detail.vue
  5. 3 0
      pages/chat/message.vue

+ 4 - 1
App.vue

@@ -62,6 +62,9 @@
 
 		onShow: function(options) {
 			console.log('App Show');
+			if (this.globalData.socket != null) {
+				this.globalData.socket.restart();
+			}
 			// setTimeout(()=>{
 			//   uni.hideTabBar()  
 			// },100)
@@ -69,7 +72,7 @@
 		onHide: function() {
 			console.log('App Hide');
 			if (this.globalData.socket != null) {
-				this.globalData.socket.stop();
+				this.globalData.socket.close();
 			}
 		},
 		onAppBackground() {},

+ 127 - 52
common/websocketUtil.js

@@ -20,7 +20,7 @@ class websocketUtil {
 		this.is_open_socket = false; //避免重复连接
 		this.url = url; //地址
 		this.data = null;
-		this.uuid = uuid;
+		this.uuid = getApp().globalData.uuid;
 		//心跳检测
 		this.timeout = 10000;
 		this.heartbeatInterval = null; //检测服务器端是否还活着
@@ -66,7 +66,8 @@ class websocketUtil {
 		// 自身巡检频率
 		let reconnect_timeout = 30000
 		//停止发送心跳
-		this.heartbeatInterval && clearInterval(this.heartbeatInterval)
+		// this.heartbeatInterval && clearInterval(this.heartbeatInterval)
+		this.reconnectTimeOut && clearTimeout(this.reconnectTimeOut)
 		if (this.socketStatus < 10) {
 			// 失败重连
 			if (this.reconnectNum > 50) return;
@@ -88,7 +89,7 @@ class websocketUtil {
 
 			return;
 		}
-		console.log("uniWebsocket 自身巡检", socketStatus, reconnectNum, reconnect_timeout)
+		console.log("uniWebsocket 自身巡检", this.socketStatus, this.reconnectNum, reconnect_timeout)
 
 		// 自身巡检循环
 		this.reconnectTimeOut = setTimeout(() => {
@@ -112,27 +113,59 @@ class websocketUtil {
 	}
 	// 进入这个页面的时候创建websocket连接【整个页面随时使用】
 	connectSocketInit() {
-		if (this.is_open_socket) {
-			return null;
-		}
+		if (!this.netIsConnected || this.netType == 'none') return
+		if (this.socketStatus > 0) return
+		// if(!url) return
+		// if (this.is_open_socket) {
+		// 	return null;
+		// }
+		this.heartbeatInterval && clearInterval(this.heartbeatInterval)
+		this.socketStatus = 1;
+		uni.onSocketError(function(res) {
+			that.socketStatus = 0;
+			console.log('WebSocket 连接错误!', that.socketStatus, res);
+		});
 		let that = this;
+
+
+		uni.onSocketClose(function(res) {
+			that.socketStatus = 0;
+			that.restart();
+			console.log('WebSocket 连接关闭!', res);
+		});
+
+		uni.onSocketOpen(function(res) {
+			that.socketStatus = 10;
+			console.log('WebSocket 连接打开!', res);
+		});
+
 		this.socketTask = uni.connectSocket({
-			url: this.url,
+			url: that.url,
 			success: () => {
+				that.socketStatus = 2;
 				console.log("正准备建立websocket中...");
-				// 返回实例
-				return this.socketTask
+				return that.socketTask;
+			},
+			fail: (data) => {
+				that.socketStatus = 0;
+				console.log("websocket 建立失败...");
 			},
+			complete: (data) => {
+				that.socketStatus = 3;
+				console.log("websocket 建立完成...");
+			}
 		});
 		this.socketTask.onOpen((res) => {
 			console.log("WebSocket连接正常!");
-			clearTimeout(this.reconnectTimeOut)
-			clearInterval(this.heartbeatInterval)
-			this.is_open_socket = true;
-			this.start();
+			// clearTimeout(this.reconnectTimeOut)
+			// clearInterval(this.heartbeatInterval)
+			that.socketStatus = 10;
+			that.reconnectNum = 0;
+			that.is_open_socket = true;
+			that.start();
 			console.log("WebSocket连接正常!-start");
 			// 注:只有连接正常打开中 ,才能正常收到消息
-			this.socketTask.onMessage((res) => {
+			that.socketTask.onMessage((res) => {
 				let resdata = JSON.parse(res.data)
 				//{"seq":"859a0fbd-05c5-4630-a160-e3cf284ad9c9","cmd":"login","response":{"code":200,"codeMsg":"{userId:'1',msg:'欢迎进入~'}","data":null}}
 				console.log(resdata)
@@ -147,6 +180,8 @@ class websocketUtil {
 					uni.$emit('updateGroup', "") //重新加入群组,以便接收消息
 				} else if (resdata.cmd == "msg") {
 					uni.$emit('messageUpdate', resdata.response.data.msg)
+				} else if (resdata.cmd == "sendMsg") {
+					uni.$emit('messageSend', resdata.response)
 				} else if (resdata.cmd == "heartbeat") {
 					if (resdata.response.code == 1000) {
 						that.toLogin();
@@ -167,8 +202,8 @@ class websocketUtil {
 		// 这里仅是事件监听【如果socket关闭了会执行】
 		this.socketTask.onClose(() => {
 			console.log("已经被关闭了")
-			this.is_open_socket = false;
-			this.reconnect();
+			that.is_open_socket = false;
+			that.reconnect();
 		})
 	}
 	toLogin() {
@@ -185,30 +220,65 @@ class websocketUtil {
 
 	//发送消息
 	send(value) {
-		console.log("send-content:", value);
 		value.seq = this.generateSeq();
-		// 注:只有连接正常打开中 ,才能正常成功发送消息
+		value = JSON.stringify(value)
+		this.msgQueue.push(value);
+
+		if (this.socketStatus < 10) {
+			console.log("**********", "连接错误,消息发送失败", value);
+			return;
+		}
 		let that = this;
-		this.socketTask.send({
-			data: JSON.stringify(value),
-			async success() {
-				// console.log("消息发送成功");
-			},
-			fail(e) {
-				console.log("send-err:", e);
-				// {"errMsg":"sendSocketMessage:fail WebSocket is not connected"}  at common/websocketUtil.js:111
-				if (e.errMsg.includes("fail WebSocket") || e.errMsg.includes("not connected")) {
-					uni.closeSocket();
-					that.reconnect();
-					console.log('is now reconnect');
-					// console.log(`"${str}" 包含 "${substr}"`);
-				} else {
-					console.log('errMsg', e.errMsg)
-					// console.log(`"${str}" 不包含 "${substr}"`);
+		let msg = '';
+		while (msg = this.msgQueue.shift()) {
+			// 注:只有连接正常打开中 ,才能正常成功发送消息
+			that.socketTask.send({
+				data: msg,
+				async success() {
+					console.log('++++++++++', msg)
+					// console.log("消息发送成功");
+				},
+				fail(e) {
+					console.log("send-err:", e);
+					//errMsg sendSocketMessage:fail Error: SocketTask.readyState is not OPEN
+					// {"errMsg":"sendSocketMessage:fail WebSocket is not connected"}  at common/websocketUtil.js:111
+					if (e.errMsg.includes("not OPEN") || e.errMsg.includes("fail WebSocket") || e.errMsg
+						.includes("not connected")) {
+						that.restart();
+						console.log('is now reconnect');
+						// console.log(`"${str}" 包含 "${substr}"`);
+					} else {
+						console.log('errMsg', e.errMsg)
+						// console.log(`"${str}" 不包含 "${substr}"`);
+					}
 				}
-			}
+			});
+		}
+		// 注:只有连接正常打开中 ,才能正常成功发送消息
+		// let that = this;
+		// this.socketTask.send({
+		// 	data: JSON.stringify(value),
+		// 	async success() {
+		// 		// console.log("消息发送成功");
+		// 	},
+		// 	fail(e) {
+		// 		console.log("send-err:", e);
+		// 		// {"errMsg":"sendSocketMessage:fail WebSocket is not connected"}  at common/websocketUtil.js:111
+		// 		if (e.errMsg.includes("fail WebSocket") || e.errMsg.includes("not connected")) {
+		// 			uni.closeSocket();
+		// 			that.reconnect();
+		// 			console.log('is now reconnect');
+		// 			// console.log(`"${str}" 包含 "${substr}"`);
+		// 		} else {
+		// 			console.log('errMsg', e.errMsg)
+		// 			// console.log(`"${str}" 不包含 "${substr}"`);
+		// 		}
+		// 	}
 
-		});
+		// });
+	}
+	getStatus() {
+		return this.socketStatus
 	}
 	//开启心跳检测
 	start() {
@@ -221,21 +291,23 @@ class websocketUtil {
 			seq: that.generateSeq(),
 			cmd: "login",
 			data: {
-				"skey": that.uuid,
+				"uuid": that.uuid,
 				"appId": 101
 			}
 		});
 		this.heartbeatInterval = setInterval(() => {
 			// console.log("heart",that.timeout);
 			//{"seq":"1565336219141-266129","cmd":"login","data":{"userId":"马远","appId":101}}
-			that.send({
-				seq: that.generateSeq(),
-				cmd: "heartbeat",
-				data: {
-					"userId": getApp().globalData.userId,
-					"appId": 101
-				}
-			});
+			if (that.socketStatus >= 10) {
+				that.send({
+					seq: that.generateSeq(),
+					cmd: "heartbeat",
+					data: {
+						"userId": getApp().globalData.userId,
+						"appId": 101
+					}
+				});
+			}
 		}, that.timeout)
 	}
 	/**
@@ -248,7 +320,7 @@ class websocketUtil {
 			return;
 		}
 
-		autoFlag = true
+		this.autoFlag = true
 
 		this.reconnect()
 
@@ -273,14 +345,17 @@ class websocketUtil {
 
 	}
 
-	stop() {
-		uni.closeSocket();
-	}
+	// stop() {
+	// 	uni.closeSocket();
+	// }
 	//外部获取消息
 	getMessage(callback) {
-		this.socketTask.onMessage((res) => {
-			return callback(res)
-		})
+		console.log("message", this.socketTask);
+		if (this.socketTask != null) {
+			this.socketTask.onMessage((res) => {
+				return callback(res)
+			})
+		}
 	}
 
 }

+ 1 - 1
pages/chat/components/message.vue

@@ -141,7 +141,7 @@
 					date = e.create_time;
 
 					// 是否是自己
-					e._isMy = e.from == this.userInfo.userId;
+					e._isMy = e.from == getApp().globalData.userId;
 
 					if (e._isMy) {
 						e.avatarUrl = e.avatar;

+ 63 - 44
pages/chat/detail.vue

@@ -238,7 +238,7 @@
 			uni.$on('updateGroup', this.addGroup)
 			uni.$on('messageUpdate', this.acceptMessage)
 			uni.$on('sendMessage', this.sendMessage)
-
+			uni.$on('messageSend', this.messageSend) //发送状态返回
 			uni.$on('messageProgress', this.messageProgress)
 		},
 		computed: {
@@ -610,60 +610,79 @@
 			// 发送消息
 			onTextSend() {
 				if (this.value) {
-					// console.log('-v:', this.value)
-					uni.request({
-						url: this.$apiHost2 + '/Chat/sendMessage', //仅为示例,并非真实接口地址。
+					uni.showLoading({})
+					setTimeout(function() {
+						uni.hideLoading()
+					}, 5000)
+					getApp().globalData.socket.send({
+						cmd: "sendMsg",
 						data: {
-							uuid: getApp().globalData.uuid,
-							userID: this.userID,
-							conversationID: this.conversationID,
-							conversationType: this.conversationType,
-							message: this.value
-						},
-						header: {
-							'content-type': 'application/json' //自定义请求头信息
-						},
-						success: (res) => {
-							console.log("----", res.data);
-							if (res.data.success == "yes") {
-								if (res.data.conversation_id != "") {
-									this.conversationID = res.data.conversation_id;
-								}
-							}
-
-
+							"uuid": getApp().globalData.uuid,
+							"appId": 101,
+							"mode": "text",
+							"userID": this.userID,
+							"conversationID": this.conversationID,
+							"conversationType": this.conversationType,
+							"message": this.value
 						}
 					});
+					// console.log('-v:', this.value)
+					// uni.request({
+					// 	url: this.$apiHost2 + '/Chat/sendMessage', //仅为示例,并非真实接口地址。
+					// 	data: {
+					// 		uuid: getApp().globalData.uuid,
+					// 		userID: this.userID,
+					// 		conversationID: this.conversationID,
+					// 		conversationType: this.conversationType,
+					// 		message: this.value
+					// 	},
+					// 	header: {
+					// 		'content-type': 'application/json' //自定义请求头信息
+					// 	},
+					// 	success: (res) => {
+					// 		console.log("----", res.data);
+					// 		if (res.data.success == "yes") {
+					// 			if (res.data.conversation_id != "") {
+					// 				this.conversationID = res.data.conversation_id;
+					// 			}
+					// 		}
+
+
+					// 	}
+					// });
 					// this.TIM.sendTextMessage(this.value, this.userID, this.conversationType);
 					this.value = "";
 				}
 			},
-			sendMessage(msg) { //暂时没用到
-				uni.request({
-					url: this.$apiHost2 + '/Chat/sendMessage', //仅为示例,并非真实接口地址。
+			sendMessage(msg) { //发送图片
+				getApp().globalData.socket.send({
+					cmd: "sendMsg",
 					data: {
-						uuid: getApp().globalData.uuid,
-						mode: msg.mode,
-						conversationID: this.conversationID,
-						conversationType: this.conversationType,
-						message: msg.message
-					},
-					header: {
-						'content-type': 'application/json' //自定义请求头信息
-					},
-					success: (res) => {
-						// console.log("this.skey", this.skey);
-						console.log("----", res.data);
-						if (res.data.success == "yes") {
-							if (res.data.conversationID != "") {
-								this.conversationID = res.data.conversationID;
-							}
-						}
-
-
+						"uuid": getApp().globalData.uuid,
+						"appId": 101,
+						"mode": msg.mode,
+						"userID": this.userID,
+						"conversationID": this.conversationID,
+						"conversationType": this.conversationType,
+						"message": msg.message
 					}
 				});
 			},
+			messageSend(msg) {
+				console.log("messageSend:", msg);
+				uni.hideLoading()
+				if (msg.code == 200) {
+					if (msg.codeMsg != "") {
+						this.conversationID = msg.codeMsg;
+					}
+				} else {
+					getApp().globalData.socket.restart();
+					uni.showToast({
+						title: msg.codeMsg,
+						icon: 'none'
+					});
+				}
+			},
 
 			hackMessage() {
 				if (this.list.length > 0) {

+ 3 - 0
pages/chat/message.vue

@@ -177,6 +177,9 @@
 					}
 				});
 			}
+			if (getApp().globalData.socket != null) {
+				getApp().globalData.socket.restart();
+			}
 			this.loadData();
 			this.loadSystemMsg();
 		},