Skip to content

Commit 08d28d9

Browse files
committed
fix: Refine WebSocket connection management logic
adds guards to the heartbeat interval to prevent a send with an invalid socket updates connection timeout to use the connection timeout option uses clearTimeout for setTimeout and clearInterval for setInterval
1 parent b2a49fa commit 08d28d9

1 file changed

Lines changed: 21 additions & 4 deletions

File tree

src/events/EventClient.ts

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -153,7 +153,7 @@ export class EventClient<
153153

154154
this.#connectTimeoutReference = setTimeout(
155155
() => this.disconnect(),
156-
this.options.pongTimeout * 1e3,
156+
this.options.connectTimeout * 1e3,
157157
) as never;
158158

159159
const url = new URL(uri);
@@ -178,8 +178,25 @@ export class EventClient<
178178
this.#socket = new WebSocket(url);
179179

180180
this.#socket.onopen = () => {
181+
clearInterval(this.#heartbeatIntervalReference);
182+
clearTimeout(this.#pongTimeoutReference);
183+
clearTimeout(this.#connectTimeoutReference);
181184
this.#heartbeatIntervalReference = setInterval(() => {
185+
if (!this.#socket) {
186+
clearInterval(this.#heartbeatIntervalReference);
187+
clearTimeout(this.#pongTimeoutReference);
188+
return;
189+
}
190+
if (this.#socket.readyState === WebSocket.CONNECTING) {
191+
return;
192+
}
193+
if (this.#socket.readyState !== WebSocket.OPEN) {
194+
clearInterval(this.#heartbeatIntervalReference);
195+
clearTimeout(this.#pongTimeoutReference);
196+
return;
197+
}
182198
this.send({ type: "Ping", data: +new Date() });
199+
clearTimeout(this.#pongTimeoutReference);
183200
this.#pongTimeoutReference = setTimeout(
184201
() => this.disconnect(),
185202
this.options.pongTimeout * 1e3,
@@ -193,7 +210,7 @@ export class EventClient<
193210
};
194211

195212
this.#socket.onmessage = (event) => {
196-
clearInterval(this.#connectTimeoutReference);
213+
clearTimeout(this.#connectTimeoutReference);
197214

198215
if (this.#transportFormat === "json") {
199216
if (typeof event.data === "string") {
@@ -218,8 +235,8 @@ export class EventClient<
218235
disconnect(): void {
219236
if (!this.#socket) return;
220237
clearInterval(this.#heartbeatIntervalReference);
221-
clearInterval(this.#connectTimeoutReference);
222-
clearInterval(this.#pongTimeoutReference);
238+
clearTimeout(this.#connectTimeoutReference);
239+
clearTimeout(this.#pongTimeoutReference);
223240
const socket = this.#socket;
224241
this.#socket = undefined;
225242
socket.close();

0 commit comments

Comments
 (0)