欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 养生 > 支付宝小程序websocket长连接(心跳版本)

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

2024/11/30 12:48:41 来源:https://blog.csdn.net/weixin_44705979/article/details/141431325  浏览:    关键词:支付宝小程序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 = falsethis.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 = falsethis.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 : 165this.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.效果
在这里插入图片描述

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com