支付宝小程序websocket长连接(心跳版本)

注意点:
关闭连接一定要把那些开下来的监听全部关闭掉

1.开启连接

			/*长连接*/
connectWebSocket() {
				let that = this;
				my.connectSocket({
					url: `ws://192.xx.8.xx:7780/charger-service-netty/websocket/${uni.getStorageSync('chargePointId')}`,
					header: {
						AccessType: 'alipay-mini-program',
						Authorization: uni.getStorageSync("token")
					},
					success: (res) => {
						console.log("创建socket连接成功" + JSON.stringify(res));
						console.log('1111111')

					},
					fail: (error) => {
						console.error('创建连接失败: ', JSON.stringify(error));
					},
				});
				// 连接建立时的事件监听器
				my.onSocketOpen(function(res) {
					console.log('2222222')
					console.log('WebSocket 连接已打开!', JSON.stringify(res));
				});
				// 监听长连接消息回调
				my.onSocketMessage((res) => {
					console.log('3333333')
					console.log('onSocketMessage 接收到了消息', JSON.parse(res.data));
					let resp = JSON.parse(res.data)
					if (resp.action == 'ConnectedSuccess') { // 连接成功标识
						that.webSocketFlag = true;

					}
					if (resp.action == 'RemoteStartTransaction') { // 开始充电失败
						if (resp.success == 1) { // 失败
							uni.showToast({
								title: resp.message
							})
							this.loadingFlag = false
						}
					}
					if (resp.action == 'RemoteStopTransaction') { // 停止充电失败
						if (resp.success == 1) { // 失败
							uni.showToast({
								title: resp.message
							})
							this.loadingFlag = false
						}
					}
					if (resp.action == 'StartTransaction') { //开始充电成功
						if (resp.success == 0) { // 充电成功
							this.loadingFlag = false
							this.chargingFlag = true;
							uni.showToast({
								title: '已开始充电'
							})
							uni.setStorageSync('chargingFlag', true)
						} else {
							uni.showToast({
								title: resp.message
							})
							this.loadingFlag = false
						}
					}
					if (resp.action == 'StopTransaction') { //停止充电成功
						if (resp.success == 0) { // 充电成功
							this.loadingFlag = false
							this.chargingFlag = false;
							uni.showToast({
								title: '已停止充电'
							})
							uni.setStorageSync('chargingFlag', false)
						} else {
							uni.showToast({
								title: resp.message
							})
							this.loadingFlag = false
						}
					}
					if (resp.action == 'StatusNotification') { // 上报桩状态
						if (resp.success == 0) {
							this.guntStatus = resp.payload.connectorStatusCode // 枪状态
						}
					}
					if (resp.action == 'MeterValues') {
						if (resp.success == 0) {
							this.currentData = resp.payload
							// 格式化充电时间
							if (this.currentData.chargeDuration == 0) {
								this.currentData.chargeDurationStr = '- -'
							} else if (this.currentData.chargeDuration > 0 && this.currentData.chargeDuration <
								3600) {
								this.currentData.chargeDurationStr = Math.floor(this.currentData.chargeDuration /
									60) + 'min'
							} else {
								let hours = Math.floor(this.currentData.chargeDuration / 3600);
								let min = Math.floor((this.currentData.chargeDuration % 3600) / 60);
								this.currentData.chargeDurationStr = hours + 'h' + min + 'min'
							}
							
							// 格式化蚂蚁能量
							if (this.currentData.greenEnergyPer != '') {
								let perCount = parseFloat(this.currentData.greenEnergyPer)
								let baseHeight = perCount == 100 ? 168 : 165
								this.energyHeight = -(perCount * 0.35 + baseHeight) //计算小球波浪的高度
							}
						}
					}
				});
				// 连接错误时的事件监听器
				my.onSocketError(function(res) {
					console.log('onSocketError' + JSON.parse(res.data))
					that.restConnect()
				});

				// 连接关闭时的事件监听器
				my.onSocketClose(function(res) {
					console.log('onSocketClose' + JSON.parse(res.data))
					that.webSocketFlag = false;
					that.restConnect()
				})
			},

2.心跳

			// webSocket 发送心跳
			heartStart() {
				console.log('准备开始发送心跳')
				let that = this;
				if (this.webSocketFlag) {
					my.sendSocketMessage({
						data: JSON.stringify({
							heartbeat: 1,
						}),
						fail: (error) => {
							console.error('sendSocketMessage failed: ', JSON.stringify(error));
							that.restConnect()
						},
						success: (res) => {
							console.log('心跳指令下发成功')
							console.log(res)
							that.webSocketTimer = setTimeout(() => {
								that.heartStart()
							}, 30000)
						}
					})
				} else {
					if (that.webSocketTimer != null) {
						clearTimeout(that.webSocketTimer)
						that.webSocketTimer = null;
					}
				}
			},

3.重新连接

		/*重新连接*/
			restConnect() {
				console.log('开始重新连接了')
				let that = this;
				that.webSocketFlag = false;
				clearTimeout(that.webSocketTimer)
				that.webSocketTimer = null;
				that.closeWebsocket()
				let timer = setTimeout(() => {
					that.connectWebSocket()
					clearTimeout(timer)
					timer = null;
					console.log('长连接断开了,开始重新连接')
				}, 2000)
			},

4.离开页面关闭连接

	// 关闭websocket连接
			closeWebsocket() {
				let that = this;
				my.offSocketMessage(); // 取消监听 WebSocket 接收到服务器的消息事件。
				my.offSocketOpen() // 取消监听 WebSocket 连接打开事件
				// 监听 WebSocket 连接关闭事件
				my.onSocketClose(function(res) {
					console.log('socket 连接已关闭!')
				});

				// 关闭 socket 连接
				my.closeSocket({
					success: () => {
						console.log('socket++关闭成功');
						that.webSocketFlag = false;
					}
				})
			},

5.效果
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值