Skip to content

Commit

Permalink
Merge pull request #130 from GreenAsJade/ping_timeout_event
Browse files Browse the repository at this point in the history
Ping timeout event
  • Loading branch information
anoek authored Oct 2, 2023
2 parents 081aecc + 1c59048 commit 2831055
Showing 1 changed file with 15 additions and 0 deletions.
15 changes: 15 additions & 0 deletions src/GobanSocket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ export interface GobanSocketEvents extends ServerToClient {
/* Emitted when we receive an updated latency measurement */
latency: (latency: number, clock_drift: number) => void;

/* Emitted when the time since ping exceeds options.timeout_delay */
timeout: () => void;
//[key: string]: (...data: any[]) => void;
}

Expand All @@ -44,6 +46,7 @@ interface GobanSocketOptions {
dont_ping?: boolean;

ping_interval?: number; // milliseconds
timeout_delay?: number;

/** Don't log connection/disconnect things*/
quiet?: boolean;
Expand Down Expand Up @@ -99,6 +102,7 @@ export class GobanSocket<
private reconnect_tries = 0;
private send_queue: (() => void)[] = [];
private ping_timer?: ReturnType<typeof niceInterval>;
private timeout_timer?: ReturnType<typeof setTimeout>;
private callbacks: Map<number, (data?: any, error?: ErrorResponse) => void> = new Map();
private authentication?: DataArgument<SendProtocol["authenticate"]>;
private manually_disconnected = false;
Expand All @@ -120,6 +124,7 @@ export class GobanSocket<
this.latency = latency;
this.clock_drift = drift;
this.emit("latency", latency, drift);
clearTimeout(this.timeout_timer);
///console.log("Pong:", this.url);
});
}
Expand All @@ -139,6 +144,10 @@ export class GobanSocket<
}
}

signalTimeout = () => {
this.emit("timeout");
};

private startPing(): void {
if (!this.connected) {
throw new Error("GobanSocket not connected");
Expand All @@ -155,6 +164,9 @@ export class GobanSocket<
drift: this.clock_drift,
latency: this.latency,
} as DataArgument<SendProtocol["net/ping"]>);
if (this.options.timeout_delay) {
this.timeout_timer = setTimeout(this.signalTimeout, this.options.timeout_delay);
}
} else {
if (this.ping_timer) {
clearInterval(this.ping_timer);
Expand All @@ -166,6 +178,9 @@ export class GobanSocket<
if (this.ping_timer) {
clearInterval(this.ping_timer);
}
if (this.timeout_timer) {
clearTimeout(this.timeout_timer);
}

this.ping_timer = niceInterval(ping, this.options.ping_interval ?? PING_INTERVAL);
ping();
Expand Down

0 comments on commit 2831055

Please sign in to comment.