利用vuex做頁面級通訊辽故,利用websocket接收監(jiān)聽消息幌墓,利用http做接口交互
其中config是一些基本的應(yīng)用配置
ChatModel是封裝的一些http接口
本文主要分享的是uni-app websocket封裝的類
可以根據(jù)自己的業(yè)務(wù)拿來改改就能用了
import store from '@/store/index.js'
import config from './app_config.js'
import ChatModel from './chatModel.js'
class Chat{
//初始化
constructor() {
this.chatModel = new ChatModel();
//用戶登陸token
this.wsAccessToken = store.getters.wsAccessToken;
//ws地址
this.wsUrl = config.wsUrl + '?access_token=' + this.wsAccessToken;
//websocket對象
this.socketTask = null;
//心跳檢測
this.heartbeatInterval= null;
//心跳檢測時間
this.heartbeatTimeOut= 5000;
//是否人為關(guān)閉
this.isPeopleClose = false;
//斷線重連機制
this.reconnectInterval= null;
//重連時間
this.reconnectTimeOut= 5000;
//重連次數(shù)
this.reconnectCount = 5;
//落網(wǎng)重連
uni.onNetworkStatusChange((res) => {
if(res.isConnected){
this.connect();
}
});
}
//單例模式
static getInstance(){
if(!this.instance){
this.instance = new Chat();
}
return this.instance;
}
//鏈接并打開
connect(){
try{
this.socketTask = uni.connectSocket({
url: this.wsUrl,
success:()=>{
console.log("正在建立鏈接");
return this.socketTask
},
fail:(err)=>{
this.reconnect();
},
});
//打開鏈接正常
this.socketTask.onOpen(async (res) => {
console.log("打開鏈接成功");
//獲取會話
await this.chatModel.getSessionToken();
//獲取未讀消息
await this.chatModel.getNoReceiveMessageList();
//清除心跳and斷開重連定時器沧卢,
clearInterval(this.heartbeatInterval);
clearInterval(this.reconnectInterval);
//設(shè)置重連次數(shù)
this.reconnectCount = 5;
//重置人為關(guān)閉狀態(tài)
this.isPeopleClose = false;
//開啟心跳檢測
this.startHeartbeat();
//監(jiān)聽接收消息
this.socketTask.onMessage((res) => {
store.commit("setReceiveMessageData", res.data);
});
})
this.socketTask.onError((err) => {
console.log('onError');
})
this.socketTask.onClose(() => {
console.log('onClose');
//重連
this.reconnect();
})
}catch(e){
//重連
this.reconnect();
}
}
//發(fā)送消息
sendMsg(value){
this.socketTask.send({
data: value,
async success() {
console.log('心跳發(fā)送成功')
},
async fail(){
//重連
this.reconnect();
}
})
}
//手動關(guān)閉鏈接
close(){
console.log('close');
this.isPeopleClose = true;
this.socketTask.close({
success(res) {
console.log("手動關(guān)閉成功")
},
fail(err) {
}
})
}
//心跳檢測
startHeartbeat(){
this.heartbeatInterval = setInterval(() => {
this.sendMsg('heartbeat');
}, this.heartbeatTimeOut);
}
//斷線重連
reconnect(){
//停止發(fā)送心跳
clearInterval(this.heartbeatInterval);
//非人為關(guān)閉則嘗試重連
console.log('進行斷線重連');
if(!this.isPeopleClose){
this.reconnectInterval = setInterval(() => {
//如果重連次數(shù)小于0則清除定時器
if(this.reconnectCount > 0){
console.log('正在重連逻恐,第'+this.reconnectCount+'次');
this.connect();
this.reconnectCount--;
}else{
clearInterval(this.reconnectInterval);
}
}, this.reconnectTimeOut);
}
}
}
export default Chat;
使用攒至,可根據(jù)你自己的業(yè)務(wù)在首頁或者別的頁面進行鏈接。
<script>
import Chat from '@/utils/chat.js'
export default {
onLoad: function() {
Chat.getInstance().connect();
},
//頁面卸載罪帖,手動關(guān)閉websocket
onUnload: function() {
Chat.getInstance().close();
},
}
</script>