// 放入methods里面在 onLoad() 调用即可
connectSocketInit(){
// 创建一个this.socketTask对象(发送、接收、关闭socket都由这个对象操作)
let userInfo = uni.getStorageSync('hg_cook');
//socket地址:ws://xxx.dd.cn:6586
let socket_url = userInfo.socket_url;
uni.connectSocket({
url: socket_url,
success(data){
console.log("websocket连接成功",data);
}
});
//监听socket打开
uni.onSocketOpen(()=>{
this.is_opensocket=true
//console.log('WebSocket连接已打开!');
this.connectSocketInit();
});
//监听socket关闭
uni.onSocketClose(()=>{
this.is_opensocket=false;
this.connectSocketInit()
console.log('WebSocket连接已关闭!')
});
//监听socket错误
uni.onSocketError(()=>{
this.is_opensocket=false
this.connectSocketInit()
console.log('WebSocket连接打开失败');
});
uni.onSocketMessage((res)=>{
let str1 = res.data;
let obj = JSON.parse(str1);
//console.log(obj);
//console.log(str.id);
if(obj.receipt){
this.audioPay(obj.receipt);
let heartData = {
orderId:obj.id,
}
uni.sendSocketMessage({
data: JSON.stringify(heartData),
});
}
});
//先确保清除了之前的心跳定时器
clearInterval(this.pingpangTimes)
// 每过一段时间发送一次心跳,发送Ping,服务器会反馈pong,这样操作以保持socket一直是连接状态,防止断开连接,心跳停止
this.pingpangTimes=setInterval(()=>{
// 心跳传参
let userInfo = uni.getStorageSync('hg_cook');
//用户ID
let id = userInfo.userId;
let heartData = {
userId:id,
}
uni.sendSocketMessage({
data: JSON.stringify(heartData),
success:(res)=>{
//其实监听里面有,或者不返回跟后端,用处不大,可以删除
//console.log('心跳的返回:',res)
},
fail:(res)=>{
// console.log(res)
this.is_opensocket=false;
},
});
},3000);
},
发表评论 取消回复