import { EventHandler } from '@/Service/Comm/EventHandler'; import { Service, ImConnectService } from '@/Service/Im/ImConnectService'; export class WebSocket { private socketTask: any; private heartbeat: number = 60000; private heartbeatInterval: any; public ConnectSocketInit() { ImConnectService.GetConnect().then((res: any) => { Service.SetUserClientId(res.data.websocketId); this.socketTask = uni.connectSocket({ url: res.data.server, header: { 'content-type': 'application/json' }, success: () => { // console.log('============正准备建立websocket中================'); } }); this.socketTask.onOpen((res: any) => { console.log('==============WebSocket连接正常============='); this.start(); EventHandler.ConnectBus(); // 只有连接正常打开中 ,才能正常收到消息 this.socketTask.onMessage((data: any) => { console.log('接收到消息') EventHandler.Events(data); }); }); this.socketTask.onClose((e: any) => { console.log('========已经被关闭了====================', e); // 加了flag判断是否为手动(用户主动关闭) // e && e.reason == 'user' ? '' : this.reconnect(); }); }); } private start() { var data = { code: 'Heart', method: 'Heart' }; this.heartbeatInterval = setInterval(() => { console.log('======start====开启心跳检测====', data); this.send(JSON.stringify(data)); }, this.heartbeat); } //重新连接 public reconnect() { //停止发送心跳 clearInterval(this.heartbeatInterval); //如果不是人为关闭的话,进行重连 uni.$emit('ImCom'); } // 关闭 WebSocket 连接 public CloseSocket(reason: string) { if(!this.socketTask){ return } this.socketTask.close({ code: 1000, reason: reason, success() { clearInterval(this.heartbeatInterval); console.log('===============关闭 WebSocket 成功==================='); }, fail() { console.log('===================关闭 WebSocket 失败====================='); } }); } //发送消息 public send(value: any) { if(!this.socketTask){ return } // 连接正常打开时 ,才能正常成功发送消息 this.socketTask.send({ data: value, success() {}, fail() { this.reconnect(); } }); } }