Skip to content

Send Keep-Alive Ping Immediately When Previous Ping Is Overdue #63195

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Aug 15, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 21 additions & 8 deletions src/SignalR/clients/ts/signalr/src/HubConnection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -721,24 +721,27 @@ export class HubConnection {
// Set the timeout timer
this._timeoutHandle = setTimeout(() => this.serverTimeout(), this.serverTimeoutInMilliseconds);

// Immediately fire Keep-Alive ping if nextPing is overdue to avoid dependency on JS timers
let nextPing = this._nextKeepAlive - new Date().getTime();
if (nextPing < 0) {
if (this._connectionState === HubConnectionState.Connected) {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this._trySendPingMessage();
}
return;
}

// Set keepAlive timer if there isn't one
if (this._pingServerHandle === undefined)
{
let nextPing = this._nextKeepAlive - new Date().getTime();
if (nextPing < 0) {
nextPing = 0;
}

// The timer needs to be set from a networking callback to avoid Chrome timer throttling from causing timers to run once a minute
this._pingServerHandle = setTimeout(async () => {
if (this._connectionState === HubConnectionState.Connected) {
try {
await this._sendMessage(this._cachedPingMessage);
} catch {
// We don't care about the error. It should be seen elsewhere in the client.
// The connection is probably in a bad or closed state now, cleanup the timer so it stops triggering
this._cleanupPingTimer();
}
await this._trySendPingMessage();
}
}, nextPing);
}
Expand Down Expand Up @@ -1149,4 +1152,14 @@ export class HubConnection {
private _createCloseMessage(): CloseMessage {
return { type: MessageType.Close };
}

private async _trySendPingMessage(): Promise<void> {
try {
await this._sendMessage(this._cachedPingMessage);
} catch {
// We don't care about the error. It should be seen elsewhere in the client.
// The connection is probably in a bad or closed state now, cleanup the timer so it stops triggering
this._cleanupPingTimer();
}
}
}
Loading