首先自己进行了简单的封装,但是服务器一断开就会断掉,下面再加上心跳重连
data() {
return {
websock: null
};
},
methods: {
initWebSocket() {
const url = 'ws://127.0.0.1:8080/home';
this.websock = uni.connectSocket({
url: url,
complete: ()=> {} // 由于uni封装,必须加个回调才会返回一个SocketTask对象
});
this.websock.onOpen(this.websocketonopen)
this.websock.onMessage(this.websocketonmessage)
this.websock.onClose(this.websocketclose)
this.websock.onError(this.websocketonerror)
},
websocketonopen() { // 连接建立之后执行send方法发送数据,连接成功
const data = {
token: this.userInfo.access_token
};
if (data.token) {
const result = JSON.stringify(data);
this.websock.send({
data: result
})
} else {
this.websock.close()
}
},
websocketonmessage (e) { // 数据接收
const num = Number(JSON.parse(e.data).data);
plus.runtime.setBadgeNumber(num); // 设置角标
},
websocketclose (e) { // 关闭
console.log('已关闭连接')
},
websocketonerror () {
console.log( 'WebSocket连接失败')
}
}
注意:uni在封装websocket的时候,有很多api都会与浏览器中带的websocket对象不同,官方地址:(uni-app官网);包括在send的时候,需要组装成一个对象,将需要传递的值放在data字段里面。
下面进行优化,加上心跳重连:
data() {
return {
websock: null,
lockReconnect: false
};
},
methods: {
initWebSocket() {
const url = 'ws://127.0.0.1:8080/home';
this.websock = uni.connectSocket({
url: url,
complete: ()=> {} // 由于uni封装,必须加个回调才会返回一个SocketTask对象
});
this.websock.onOpen(this.websocketonopen)
this.websock.onMessage(this.websocketonmessage)
this.websock.onClose(this.websocketclose)
this.websock.onError(this.websocketonerror)
},
websocketonopen() { // 连接建立之后执行send方法发送数据,连接成功
const data = {
token: this.userInfo.access_token
};
if (data.token) {
const result = JSON.stringify(data);
this.websock.send({
data: result
})
} else {
this.websock.close()
}
},
websocketonmessage (e) { // 数据接收
const num = Number(JSON.parse(e.data).data);
plus.runtime.setBadgeNumber(num); // 设置角标
},
websocketclose (e) { // 关闭
if (state.userInfo) { // 用户登录还存在时再进行重连
console.log('断开了重连');
this.reconnect()
}
},
websocketonerror () {
if (state.userInfo) { // 用户登录还存在时再进行重连
console.log('断开了重连');
this.reconnect()
}
},
reconnect() {
if(this.lockReconnect) return;
this.lockReconnect = true;
//没连接上会一直重连,设置延迟避免请求过多
setTimeout(function () {
this.initWebSocket();
console.log('重连中');
this.lockReconnect = false;
}, 5000); //这里设置重连间隔(ms)
}
}