我有一个像这样设置的 SSE 连接 =>
init(channel: string, reconnecting?: boolean) {
if (this.eventSource) {
return console.warn("SSE : Already Setup");
}
console.info("SSE Channel Start");
this.channel = channel;
this.eventSource = new EventSource(HTTPUtils.getPath(`${environment.SSE_PATH}?channel=${this.channel}`));
this.eventSource.onopen = () => {
console.info("SSE : Connection OPEN");
this.state$.next(reconnecting ? SSEState.RECONNECTED : SSEState.CONNECTED);
};
this.eventSource.onerror = (error) => {
console.info("SSE : Connection Lost", error);
this.close();
this.state$.next(SSEState.RECONNECTING);
this.attemptReconnect();
};
}
现在当服务器掉线时,连接关闭,我想在他再次恢复时重新连接到服务器:
private attemptReconnect() {
if (this.retryIntervalRef) {
return;
}
let timer = 0;
this.retryIntervalRef = setInterval(() => {
timer += 1000;
if (timer > this.retryTimer) {
this.init(this.channel, true);
clearInterval(this.retryIntervalRef);
this.retryIntervalRef = null;
}
}, 1000);
}
第一次连接没问题,当服务器掉线时,调用此尝试重新连接。20 秒后,它尝试重新连接,并且 sse 打开,但它仍然停留在挂起状态:
当出现错误时,我将所有内容重置为初始状态
close() {
if (this.eventSource) {
console.info("SSE Channel Closed");
this.eventSource.close();
this.eventSource = null;
this.state$.next(SSEState.CLOSED);
this.callbacks = new Map<string, (e: any) => void>();
}
}
并重新启动相同的过程......所以我不明白为什么 SSE 仍处于挂起状态。
编辑信息:
如果我在我的应用程序尝试重新连接之前刷新,一切正常。如果我等待计时器结束重新连接,它将保持挂起状态。我无法访问 BE,所以我想知道它是否也可能是 BE 问题。任何想法都会对我有很大帮助!