基于uniapp的全局监听websocket连接及自动拨打电话号码
定义一个全局的socket类
//定义一个socket类
class WebSocket {
constructor(url) {
this.url = url
this.time=null;
}
//建立连接
connet() {
let _this = this;
uni.connectSocket({
url: _this.url,
complete: (res) => {
if (res.errMsg == 'connectSocket:ok') {
//连接成功
_this.IsConnect();
} else {
//连接失败
uni.showToast({
icon: 'none',
title: '连接失败'
})
}
}
});
}
//判断是否连接
IsConnect() {
let that = this;
uni.onSocketOpen(function(res) {
if (res) {
//说明已经连接成功了
that.SetInterval(2, '心跳检测');
that.setConnect();
}
});
}
//与后台信息建立连接
setConnect() {
let that = this;
uni.onSocketMessage(function(res) {
// let {phone}=res.data; //结构赋值取号码
let data = res.data;
if (!data.includes('连接成功')) {
that.callphone(data)
}
});
}
//心跳检测
SetInterval(delay, msg) {
clearInterval(this.time) //先清除计时器
this.time = setInterval(function() {
console.log('心跳检测')
uni.sendSocketMessage({
data: msg
});
}, delay*60000)
}
//打电话
callphone(phone) {
// #ifdef APP-PLUS
plus.device.dial(phone, false)
// #endif
}
//判断是否断开连接
onError() {
let that=this;
uni.onSocketError(function(res) {
console.log('连接断开')
that.connet()
});
}
}
export default {
socket: WebSocket
}
mian.js代码
import socket from '@/utils.js/socket';
let IO = new socket.socket('websocket连接地址');
Vue.prototype.$IO=IO;
页面内调用
onLoad() {
this.$IO.connet()
},
在app.vue中监听是否断开,断开就重连
onShow: function() {
this.$IO.onError();
},