class websocketUtils { constructor(type) { this.url = 'wss://sports.njrenzhou.cn/ws' //ws地址 拼接一下 此处用的是openId this.data = null this.isOpenSocket = false //避免重复连接 this.timeout = 10 //隔多久执行检测 单位秒(s) this.sid = uni.getStorageSync("sid") //赛事id this.type = type this.heartbeatInterval = null //检测服务器端是否还存活 this.reconnectTimeOut = null //重连之后隔多久才再次重连 try { return this.connectSocketInit() } catch (e) { console.log('===========连接错误捕获catch====================',e); this.isOpenSocket = false this.reconnect(); } } // 创建websocket连接 connectSocketInit() { this.socketTask = uni.connectSocket({ url: this.url, header: { //头部可以添加所需字段如token 'content-type': 'application/json' }, success:()=>{ console.log("============正准备建立websocket中================"); // 返回实例 return this.socketTask }, }); this.socketTask.onOpen((res) => { console.log("==============WebSocket连接正常============="); clearTimeout(this.reconnectTimeOut) clearInterval(this.heartbeatInterval) this.isOpenSocket = true; if(this.type ==2){ if(this.sid){ this.startCheck(); } }else{ if(this.sid){ this.startStatement(); } } this.start(); // 只有连接正常打开中 ,才能正常收到消息 this.socketTask.onMessage((res) => { console.log(res.data,'===============接收===onMessage===============') //全局注册uniapp事件,在任何页面都能接受到 uni.$emit('socketMessage', res) }); }) // socket关闭了会执行 此处 this.socketTask.onClose((e) => { console.log("========已经被关闭了====================",e) this.isOpenSocket = false; // 加了flag判断是否为手动(用户主动关闭) uni.$emit('onClose', 1) e && e.reason == 'user' ? '' : this.reconnect(); }) } //发送消息 send(value){ // 连接正常打开时 ,才能正常成功发送消息 this.socketTask.send({ data: value, async success() { console.log("===========消息发送成功==============="); }, }); } //开启心跳检测 start(){ this.data={cmd:"ping"} this.heartbeatInterval = setInterval(()=>{ console.log('======start====开启心跳检测====',this.data) this.send(JSON.stringify(this.data)); },this.timeout * 1000) } startStatement() { this.data={cmd:"statement",'matchs_id': this.sid} this.send(JSON.stringify(this.data)); } startCheck() { this.data={cmd:"check",'matchs_id': this.sid} this.send(JSON.stringify(this.data)); } //重新连接 reconnect(){ //停止发送心跳 clearInterval(this.heartbeatInterval) //如果不是人为关闭的话,进行重连 if(!this.isOpenSocket ){ this.reconnectTimeOut = setTimeout(()=>{ this.connectSocketInit(); },3000) } } // 关闭 WebSocket 连接 closeSocket(reason = '关闭') { const _this = this this.socketTask.close({ reason, success() { _this.data = null _this.isOpenSocket = false _this.socketTask = null clearTimeout(_this.reconnectTimeOut) clearInterval(_this.heartbeatInterval) console.log('===============关闭 WebSocket 成功===================') // setTimeout(()=>{ // uni.navigateTo({ // url: "/pages/index/index" // }) // },1000) }, fail() { console.log('===================关闭 WebSocket 失败=====================') } }) } //将获取的消息导出外部 exportMessage(callback) { this.socketTask.onMessage((res) => { console.log(res,'===============exportMessage============') return callback(res) }) } } module.exports = websocketUtils