注意点:
关闭连接一定要把那些开下来的监听全部关闭掉
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.效果