UNPKG

mmjs-core

Version:
71 lines (70 loc) 2.97 kB
var c = Object.defineProperty; var o = (r, e, t) => e in r ? c(r, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : r[e] = t; var s = (r, e, t) => o(r, typeof e != "symbol" ? e + "" : e, t); class a { constructor(e, t) { s(this, "socket"); s(this, "url"); s(this, "heartbeatInterval"); s(this, "heartbeatTimer"); s(this, "maxReconnectAttempts"); s(this, "reconnectDelay"); s(this, "reconnectAttempts"); this.url = e, this.socket = null, this.heartbeatInterval = (t == null ? void 0 : t.heartbeatInterval) ?? 3e4, this.heartbeatTimer = 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.socket.onmessage = (e) => { this.resetHeartbeat(); try { const t = JSON.parse(e.data ?? "{}"); if (t.type === "pong") { console.log("收到心跳响应"); return; } this.onMessage && this.onMessage(t); } 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.socket.onerror = (e) => { console.error("WebSocket错误:", e), this.reconnectAttempts < this.maxReconnectAttempts && (this.reconnectAttempts++, console.log(`尝试重新连接 (${this.reconnectAttempts}/${this.maxReconnectAttempts})...`), 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.stopHeartbeat(), this.startHeartbeat(); } stopHeartbeat() { this.heartbeatTimer && (clearInterval(this.heartbeatTimer), this.heartbeatTimer = null); } close() { this.stopHeartbeat(), this.socket && this.socket.close(); } // 回调函数 onOpen(e) { } onMessage(e) { } onClose(e) { } onError(e) { } } export { a as WebSocketClient };