注意: 在app.vue onLaunch中调用webSocket这样可以一进入系统就开启webSocket。
步骤: 判断是否已连接 --> 如未连接 打开连接(已连接就跳过) --> 打开成功监听服务器返回的消息 -->前端用户跟服务器进行绑定 --> 监听到有新服务器消息,对服务器返回的新消息进行操作 --> 检测心跳 --> 心跳已停止重新连接websocket

data() {
	return {
			timeout: 60000, // 1分钟
			timeoutObj: null,
		}
},
onLaunch () {
		// .判断是否已连接
		this.checkOpenSocket(); 
},
methods:  {
 // 判断是否已连接
	checkOpenSocket () {
				let self = this;
				uni.sendSocketMessage({
					data: 'ping',
					 success: (res) => {
						return;
					},
					fail: (err) => { // 未连接打开websocket连接
						self.openConnection(); 
					}
				});
			},
		openConnection () { // 打开连接
				uni.closeSocket(); // 确保已经关闭后再重新打开
				uni.connectSocket({
					url: this.$SOCKTURL,
					method: 'POST',
					success(res) {
						console.log('连接成功 connectSocket=', res);
					},
					fail(err) {
						console.log('连接失败 connectSocket=', err);
					}
				});
				uni.onSocketOpen((res) => {
					console.log('连接成功', res);
				});
				this.onSocketMessage(2); // 打开成功监听服务器返回的消息
			},
		//	打开成功监听服务器返回的消息
		onSocketMessage (type = 1) { // 消息
				this.timeout = 60000;
				this.timeoutObj = null;
				uni.onSocketMessage((res) => {
					let giveMsg = res.data;
					// 后台绑定client_id
					if (giveMsg) {
						let msg = JSON.parse(giveMsg);
						if (msg.type ===  'init' && type === 2) {
							let clientId =  msg.client_id;
							let userId = uni.getStorageSync('userInfo');
							let para = {client_id: clientId, userId : userId  };
							uni.request({ // 前端用户跟服务器进行绑定
								url:  `htpp:/localhost:8080/v2/conference/user_binding'`,
								data: para,
							success: (res) => { // 绑定成功
								if (res.statusCode === 200) {
								this.reset(); // // 检测心跳reset,防止长时间连接导致连接关闭
								}
							}
						 });
						  // 有消息内容
						 if (msg.type ==  'content') {
							this.getSocketMsg(msg.data); // 监听到有新服务器消息
						}
					}
				});
			},
			// 监听到有新服务器消息
			getSocketMsg (reData) { // 监听到服务器消息
				console.log('监听到服务器消息 reData=', reData);
				let info = JSON.parse(reData);
				if (info.type  === 'notice') {
					console.log(info);
					 let options = {cover: false, title: info.time};
					 // #ifdef APP-PLUS
						plus.push.createMessage(info.content, info, options); // 弹出到状态栏中
					 // #endif
				 }	 
				console.log('app onMessage=', reData)
			},
			// 检测心跳reset
			reset () {
				clearInterval(this.timeoutObj);
				this.start(); // 启动心跳
			},
			// 启动心跳 start 
			start () {
				let self = this;
				this.timeoutObj = setInterval(function(){
					uni.sendSocketMessage({
						data: 'ping',
						 success: (res) => {
							console.log('连接中....');
						},
						fail: (err) => {
							console.log('连接失败重新连接....');
							self.openConnection();
						}
					});
				}, this.timeout);
			}
		},
}
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐