uni-app 使用封装单例websocket 类 心跳检测 断开重连 落网重连 即时通讯

利用vuex做页面级通讯,利用websocket接收监听消息,利用http做接口交互
其中config是一些基本的应用配置
ChatModel是封装的一些http接口
本文主要分享的是uni-app websocket封装的类
可以根据自己的业务拿来改改就能用了

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; 
        
        //是否人为关闭
        this.isPeopleClose = false;
        //断线重连机制
        this.reconnectInterval= null;
        //重连时间
        this.reconnectTimeOut= 5000; 
        //重连次数
        this.reconnectCount = 5;
        
        //落网重连
        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);
                //设置重连次数
                this.reconnectCount = 5;
                //重置人为关闭状态
                this.isPeopleClose = false;
                
                //开启心跳检测
                this.startHeartbeat();
                
                //监听接收消息
                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();
        }
    }
    //发送消息
    sendMsg(value){
        this.socketTask.send({
            data: value,
            async success() {
                console.log('心跳发送成功')
            },
            async fail(){
                //重连
                this.reconnect();
            }
        })
    }
    //手动关闭链接
    close(){
        console.log('close');
        this.isPeopleClose = true;
        this.socketTask.close({
            success(res) {
                console.log("手动关闭成功")
            },
            fail(err) {
                
            }
        })
    }
    //心跳检测
    startHeartbeat(){
        this.heartbeatInterval = setInterval(() => {
            this.sendMsg('heartbeat');
        }, this.heartbeatTimeOut);
    }
    //断线重连
    reconnect(){
        //停止发送心跳
        clearInterval(this.heartbeatInterval);
        //非人为关闭则尝试重连
        console.log('进行断线重连');
        if(!this.isPeopleClose){
            this.reconnectInterval = setInterval(() => {
                //如果重连次数小于0则清除定时器
                if(this.reconnectCount > 0){
                    console.log('正在重连,第'+this.reconnectCount+'次');
                    this.connect();
                    this.reconnectCount--;
                }else{
                    clearInterval(this.reconnectInterval);
                }
            }, this.reconnectTimeOut);
        }
    }
}

export default Chat;

使用,可根据你自己的业务在首页或者别的页面进行链接。


你可能感兴趣的:(uni-app 使用封装单例websocket 类 心跳检测 断开重连 落网重连 即时通讯)