定义一个全局的socket类,放在util目录下
//定义一个socket类
class WebSocket {
constructor(url) {
this.url = url
this.time=null;
}
//建立连接
connet() {
let _this = this;
uni.connectSocket({
url: _this.url,
complete: (res) => {
console.log(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 data = res.data;
console.log("WebSocket 收到消息:" + data);
try {
JSON.parse(data);
data = JSON.parse(data) ? JSON.parse(data) : data;
} catch {
console.log('ws接收到非对象数据', data);
return true;
}
var type = data.type || '';
switch(type){
case 'get_client_id':
that.bindUid(data.data.client_id);
break;
case "call_mobile":
var mobile = data.mobile;
that.callphone(mobile)
break;
}
});
}
//心跳检测
SetInterval(delay, msg) {
clearInterval(this.time) //先清除计时器
this.time = setInterval(function() {
console.log('心跳检测')
uni.sendSocketMessage({
data: msg
});
}, delay*5000)
}
//打电话
callphone(mobile) {
// #ifdef APP-PLUS
plus.device.dial(mobile, false)
// #endif
}
//判断是否断开连接
onError() {
let that=this;
uni.onSocketError(function(res) {
console.log('连接断开')
that.connet()
});
}
//绑定客户端
bindUid(client_id) {
console.log('WebSocket 绑定客户端id' + client_id);
let organise_id = uni.getStorageSync('organise_id');
let admin_id = uni.getStorageSync('admin_id');
bindSocketClient({client_id: client_id,organise_id:organise_id,admin_id:admin_id}).then(res=>{
console.log('~~~')
console.log(res)
})
}
}
export default {
socket: WebSocket
}
import { bindSocketClient } from '@/api/login.js' socket
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();
},