fix: 优化网页端不能连接的问题

This commit is contained in:
2026-07-17 21:14:45 +08:00
parent b8edd5eff5
commit 0cb6b75a54
5 changed files with 110 additions and 22 deletions

View File

@@ -18,6 +18,8 @@ export class SignalingClient {
this.ws.onopen = () => {
this.register();
this.onConnected && this.onConnected();
// 启动心跳保活:每 25 秒发送 ping防止中间代理或服务器因空闲超时断开连接
this._startHeartbeat();
};
this.ws.onmessage = (ev) => {
let msg;
@@ -28,13 +30,38 @@ export class SignalingClient {
}
this.onMessage && this.onMessage(msg);
};
this.ws.onclose = () => this.onDisconnected && this.onDisconnected();
this.ws.onerror = (e) => this.onError && this.onError(e?.message || 'WebSocket 错误');
this.ws.onclose = (ev) => {
// 记录关闭码和原因,便于诊断断连根因:
// 1000 = 正常关闭, 1001 = 离开, 1006 = 异常断开(无 close frame
// 1009 = 消息过大, 1011 = 服务端异常
console.warn('[信令] WebSocket 已关闭 code=%d reason=%s wasClean=%s',
ev.code, ev.reason || '(无)', ev.wasClean);
this._stopHeartbeat();
this.onDisconnected && this.onDisconnected(ev.code, ev.reason);
};
this.ws.onerror = (e) => {
console.error('[信令] WebSocket 错误', e);
this.onError && this.onError(e?.message || 'WebSocket 错误');
};
} catch (e) {
this.onError && this.onError(e.message);
}
}
_startHeartbeat() {
this._stopHeartbeat();
this._heartbeatTimer = setInterval(() => {
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
// 发送轻量级 ping 消息,保持连接活跃(服务端会忽略未知类型消息)
try { this.ws.send(JSON.stringify({ type: 'PING' })); } catch { /* ignore */ }
}
}, 25000);
}
_stopHeartbeat() {
if (this._heartbeatTimer) { clearInterval(this._heartbeatTimer); this._heartbeatTimer = null; }
}
register() {
this.send({
type: 'REGISTER',
@@ -79,6 +106,7 @@ export class SignalingClient {
}
disconnect() {
this._stopHeartbeat();
if (this.ws) {
this.ws.close();
this.ws = null;