uni-app 封装 websocket 并且监听心跳机制

代码

  1. 新建 socket.js , 将以下代码复制进去 ,向外暴露。

import api from '@/common/js/config.js' // 接口Api,图片地址等等配置,可根据自身情况引入,也可以直接在下面url填入你的 webSocket连接地址
class socketIO {
    constructor(data, time, url) {
        this.socketTask = null
        this.is_open_socket = false //避免重复连接
        this.url = url ? url : api.websocketUrl  //连接地址
        this.data = data ? data : null
        this.connectNum = 1 // 重连次数
        this.traderDetailIndex = 100 // traderDetailIndex ==2 重连
        this.accountStateIndex = 100 // traderDetailIndex ==1 重连
        this.followFlake = false // traderDetailIndex == true 重连
        //心跳检测
        this.timeout = time ? time : 15000 //多少秒执行检测
        this.heartbeatInterval = null //检测服务器端是否还活着
        this.reconnectTimeOut = null //重连之后多久再次重连
    }
 
    // 进入这个页面的时候创建websocket连接【整个页面随时使用】
    connectSocketInit(data) {
        this.data = data
        this.socketTask = uni.connectSocket({
            url: this.url,
            success: () => {
                console.log("正准备建立websocket中...");
                // 返回实例
                return this.socketTask
            },
        });
        this.socketTask.onOpen((res) => {
            this.connectNum = 1
            console.log("WebSocket连接正常!");
            this.send(data)
            clearInterval(this.reconnectTimeOut)
            clearInterval(this.heartbeatInterval)
            this.is_open_socket = true;
            this.start();
            // 注:只有连接正常打开中 ,才能正常收到消息
            this.socketTask.onMessage((e) => {
                // 字符串转json
                let res = JSON.parse(e.data);
                console.log("res---------->", res) // 这里 查看 推送过来的消息
                if (res.data) {
                    uni.$emit('getPositonsOrder', res); 
                }
            });
        })
        // 监听连接失败,这里代码我注释掉的原因是因为如果服务器关闭后,和下面的onclose方法一起发起重连操作,这样会导致重复连接
        uni.onSocketError((res) => {
            console.log('WebSocket连接打开失败,请检查!');
            this.socketTask = null
            this.is_open_socket = false;
            clearInterval(this.heartbeatInterval)
            clearInterval(this.reconnectTimeOut)
            uni.$off('getPositonsOrder')
            if (this.connectNum < 6) {
                uni.showToast({
                    title: `WebSocket连接失败,正尝试第${this.connectNum}次连接`,
                    icon: "none"
                })
                this.reconnect();
                this.connectNum += 1
            } else {
                uni.$emit('connectError');
                this.connectNum = 1
            }
 
        });
        // 这里仅是事件监听【如果socket关闭了会执行】
        this.socketTask.onClose(() => {
            console.log("已经被关闭了-------")
            clearInterval(this.heartbeatInterval)
            clearInterval(this.reconnectTimeOut)
            this.is_open_socket = false;
            this.socketTask = null
            uni.$off('getPositonsOrder')
            if (this.connectNum < 6) {
                this.reconnect();
            } else {
                uni.$emit('connectError');
                this.connectNum = 1
            }
 
        })
    }
    // 主动关闭socket连接
    Close() {
        if (!this.is_open_socket) {
            return
        }
        this.socketTask.close({
            success() {
                uni.showToast({
                    title: 'SocketTask 关闭成功',
                    icon: "none"
                });
            }
        });
    }
    //发送消息
    send(data) {
        console.log("data---------->", data);
        // 注:只有连接正常打开中 ,才能正常成功发送消息
        if (this.socketTask) {
            this.socketTask.send({
                data: JSON.stringify(data),
                async success() {
                    console.log("消息发送成功");
                },
            });
        }
    }
    //开启心跳检测
    start() {
        this.heartbeatInterval = setInterval(() => {
            this.send({
                "traderid": 10260,
                "type": "Ping"
            });
        }, this.timeout)
    }
    //重新连接
    reconnect() {
        //停止发送心跳
        clearInterval(this.heartbeatInterval)
        //如果不是人为关闭的话,进行重连
        if (!this.is_open_socket && (this.traderDetailIndex == 2 || this.accountStateIndex == 0 || this
            .followFlake)) {
            this.reconnectTimeOut = setInterval(() => {
                this.connectSocketInit(this.data);
            }, 5000)
        }
    }
}
module.exports = socketIO
  1. 在入口文件中 将 socketIO 挂载在 Vue 原型上 , 也可以按需引入置顶页面 。

import socketIO from '@/common/js/scoket.js'
Vue.prototype.$socketIo = new socketIO()
  1. 在需要用到webSocket的页面中使用如下方法(可根据自身业务需求进行整改)

scoketClose() {
    this.$socketIo.connectNum = 1
    const data = {
        "value1": "demo1"
        "value2": "demo2"
    }
    this.$socketIo.send(data) // 这是给后端发送特定数据 关闭推送
    this.$socketIo.Close() // 主动 关闭连接 , 不会重连
},
 
getWebsocketData() {
    // 要发送的数据包
    const data = {
        "value": "value1",
        "type": "type1"
    }
    // 打开连接
    this.$socketIo.connectSocketInit(data)
    // 接收数据
    uni.$on("getPositonsOrder", (res) => {
        this.connect = true
        const {
            Code,
            data
        } = res
        if (Code == xxxx) {
            // 根据后端传过来的数据进行 业务编写。。。
        } else {
           
        }
    })
    // 错误时做些什么
    uni.$on("connectError", () => {
        this.connect = false
        this.scoketError = true
    })
}
  1. 离开页面,记得断开连接。

onUnload() {
    this.scoketClose()
    this.$socketIo.traderDetailIndex = 100 // 初始化 tabIndex 
}

  • 4
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值