// WebSocket 连接:断线重连交给上层,这里只管收发和 RTT。 export class Net { constructor({ onOpen, onClose, onMessage }) { this.onOpen = onOpen; this.onClose = onClose; this.onMessage = onMessage; this.ws = null; this.pingId = 0; this.pingAt = 0; this.rtt = 0; this.retry = 0; this.closedByUs = false; this.outbox = []; } url() { const proto = location.protocol === "https:" ? "wss:" : "ws:"; return `${proto}//${location.host}/ws`; } connect() { if (this.ws && (this.ws.readyState === 0 || this.ws.readyState === 1)) return; this.closedByUs = false; let ws; try { ws = new WebSocket(this.url()); } catch { this.onClose?.(); return; } this.ws = ws; ws.onopen = () => { this.retry = 0; this.startPing(); const pending = this.outbox.splice(0, this.outbox.length); for (const m of pending) ws.send(JSON.stringify(m)); this.onOpen?.(); }; ws.onmessage = (ev) => { let msg; try { msg = JSON.parse(ev.data); } catch { return; } if (msg.t === "pong") { this.rtt = Math.max(0, Math.round(performance.now() - this.pingAt)); return; } this.onMessage?.(msg); }; ws.onclose = () => { this.stopPing(); if (!this.closedByUs) this.onClose?.(); }; ws.onerror = () => { /* onclose 会跟上 */ }; } send(obj) { if (this.ws && this.ws.readyState === 1) { this.ws.send(JSON.stringify(obj)); return true; } // 还没连上:排队,连上后补发(只留最近 20 条,避免积压) this.outbox.push(obj); if (this.outbox.length > 20) this.outbox.shift(); return false; } startPing() { this.stopPing(); this.pingTimer = setInterval(() => { this.pingId++; this.pingAt = performance.now(); this.send({ t: "ping", id: this.pingId }); }, 1500); } stopPing() { clearInterval(this.pingTimer); } close() { this.closedByUs = true; this.stopPing(); if (this.ws) this.ws.close(); this.ws = null; } }