export default {
data() {
return {
ws: null,
timer: null,
isCurrentPage: true
}
},
onShow() {
// 进入页面创建连接
this.initWebsocket()
},
onHide() {
// 离开当前页面关闭连接
this.isCurrentPage = false
this.closeWs()
},
methods: {
initWebsocket() {
// #ifdef H5
this.h5Websocket()
// #endif
// #ifdef APP-PLUS
this.appWebsocket()
// #endif
},
h5Websocket() {
//创建一个webSocket实例,执行后,客户端就会与服务端连接
this.ws = new WebSocket("ws://xxx?token=" + uni.getStorageSync('token'));
//当WebSocket创建成功时,触发onopen事件
const that = this;
this.ws.onopen = function() {
that.sendMsg()
}
//当客户端收到服务端发来的消息时,触发onmessage事件
this.ws.onmessage = function(e) {
//e.data 的数据格式也是字符串,手动解析这些数据才能得到其他格式的数据。
that.dataFormat(e)
}
//当客户端收到服务端发送的关闭连接请求时,触发onclose事件
this.ws.onclose = function(e) {
that.reconnect()
}
//如果出现连接、处理、接收、发送数据失败的时候触发onerror事件
this.ws.onerror = function(e) {
}
},
appWebsocket() {
let that = this
uni.connectSocket({
url: "ws://xxx?token=" + uni.getStorageSync('token')
});
uni.onSocketOpen(function(res) {
// console.log('WebSocket连接已打开!');
that.sendMsg()
});
uni.onSocketError(function(res) {
// console.log('WebSocket连接打开失败,请检查!');
});
uni.onSocketMessage(function(res) {
// console.log('收到服务器内容:');
that.dataFormat(res)
});
uni.onSocketClose(function(res) {
// console.log('WebSocket 已关闭!');
that.reconnect()
});
},
send() {
// 复杂的数据结构,在通过连接发送之前,必须进行序列化。
const json = JSON.stringify({
type: 'heartbeat'
});
// #ifdef H5
this.ws.send(json);
// #endif
// #ifdef APP-PLUS
uni.sendSocketMessage({
data: json
});
// #endif
},
reconnect() {
let that = this
clearInterval(that.timer)
that.timer = null
// 如果在当前页面外界原因关闭的需要重新连接且最多重连5次
that.isCurrentPage = -1 < (that.getCurrentRoute().path).indexOf('当前页面路由')
if (that.isCurrentPage && 5 > that.count) {
that.count++
setTimeout(() => {
that.initWebsocket()
}, 1000)
}
},
dataFormat(e) {
const newData = JSON.parse(e.data);
const data = newData.data
let that = this
// console.log(data)
// console.log('--data')
// 更新页面信息
},
closeWs() {
// #ifdef H5
this.ws.close()
this.ws = null
// #endif
// #ifdef APP-PLUS
uni.closeSocket();
// #endif
},
sendMsg(){
let that=this
that.send()
// 间隔几秒后重新发送信息
that.timer = setInterval(() => {
// 是否是当前页面
that.isCurrentPage = -1 < (that.getCurrentRoute().path).indexOf('当前页面路由')
that.send()
// 非当前页面清空定时器
if (!that.isCurrentPage) {
clearInterval(that.timer)
that.timer = null
}
}, 10000)
},
//获取当前路由
getCurrentRoute() {
let currentRoutes = getCurrentPages(); // 获取当前打开过的页面路由数组
// console.log(currentRoutes[currentRoutes.length - 1])
let currentRoute = currentRoutes[currentRoutes.length - 1].route //获取当前页面路由
let currentParam = currentRoutes[currentRoutes.length - 1].options; //获取路由参数
// 拼接参数
let param = [];
for (let key in currentParam) {
param.push(key + '=' + currentParam[key])
}
let currentPath = '/' + currentRoute;
let currentQuery = param.join('&');
if (currentQuery) currentPath += '?' + currentQuery;
return {
path: currentPath,
query: currentQuery,
}
}
}
}
参考链接:
uniapp.dcloud.net.cn/api/request…