UNPKG

mmjs-core

Version:
2 lines (1 loc) 2.8 kB
"use strict";var n=Object.defineProperty;var o=(c,r,e)=>r in c?n(c,r,{enumerable:!0,configurable:!0,writable:!0,value:e}):c[r]=e;var s=(c,r,e)=>o(c,typeof r!="symbol"?r+"":r,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("../event/emitter.js");class h extends i.EventEmitter{constructor(e,t){super();s(this,"socket");s(this,"url");s(this,"heartbeatInterval");s(this,"heartbeatTimer");s(this,"maxReconnectAttempts");s(this,"reconnectDelay");s(this,"reconnectTimer");s(this,"reconnectAttempts");this.url=e,this.socket=null,this.heartbeatInterval=(t==null?void 0:t.heartbeatInterval)??3e4,this.heartbeatTimer=null,this.reconnectTimer=null,this.reconnectAttempts=0,this.maxReconnectAttempts=(t==null?void 0:t.maxReconnectAttempts)??5,this.reconnectDelay=(t==null?void 0:t.reconnectDelay)??5e3,this.connect()}connect(){this.socket=new WebSocket(this.url),this.socket.onopen=e=>{console.log("WebSocket连接已建立"),this.reconnectAttempts=0,this.startHeartbeat(),this.onOpen&&this.onOpen(e),this.emit("open",e)},this.socket.onmessage=e=>{this.resetHeartbeat();try{const t=JSON.parse(e.data??"{}");if(t.type==="pong"){console.log("收到心跳响应");return}this.onMessage&&this.onMessage(t),this.emit("message",t,e)}catch(t){console.error("消息解析错误:",{error:t,event:e})}},this.socket.onclose=e=>{var t;console.log("WebSocket连接关闭"),this.stopHeartbeat(),(t=this.onClose)==null||t.call(this,e),this.emit("close",e)},this.socket.onerror=e=>{console.error("WebSocket错误:",e),this.emit("error",e),this.reconnectAttempts<this.maxReconnectAttempts&&(this.reconnectAttempts++,console.log(`尝试重新连接 (${this.reconnectAttempts}/${this.maxReconnectAttempts})...`),this.reconnectTimer=setTimeout(()=>this.connect(),this.reconnectDelay)),this.onError&&this.onError(e)}}send(e){this.socket&&this.socket.readyState===WebSocket.OPEN?typeof e=="string"?this.socket.send(e):e instanceof Blob?this.socket.send(e):e instanceof ArrayBuffer||ArrayBuffer.isView(e)?this.socket.send(e):this.socket.send(JSON.stringify(e)):console.error("WebSocket未连接,无法发送消息")}startHeartbeat(){this.stopHeartbeat(),this.heartbeatTimer=setInterval(()=>{var e;((e=this.socket)==null?void 0:e.readyState)===WebSocket.OPEN&&(console.log("发送心跳"),this.send({type:"ping",timestamp:Date.now()}))},this.heartbeatInterval)}resetHeartbeat(){this.stopReconnect(),this.stopHeartbeat(),this.startHeartbeat()}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}stopReconnect(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}close(){this.stopReconnect(),this.stopHeartbeat(),this.socket&&this.socket.close()}onOpen(e){}onMessage(e){}onClose(e){}onError(e){}}exports.WebSocketClient=h;