-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
fcf24ed
commit 3cb13a0
Showing
3 changed files
with
64 additions
and
27 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
import { ClientSocket } from './socket' | ||
|
||
const avg = (values: number[]) => values.reduce((a, b) => a + b) / values.length | ||
|
||
export default class Ping { | ||
#socket: ClientSocket | ||
|
||
#timeout: NodeJS.Timeout | undefined | ||
|
||
readonly #pings: number[] | ||
|
||
constructor(socket: ClientSocket) { | ||
this.#socket = socket | ||
this.#pings = [] | ||
} | ||
|
||
#update() { | ||
const start = Date.now() | ||
|
||
this.#socket.emit('ping', () => { | ||
this.#pings.push(Date.now() - start) | ||
|
||
while (this.#pings.length > 10) { | ||
this.#pings.shift() | ||
} | ||
|
||
// TODO: make calculations on demand and extract/remove logging of ping | ||
const ping = Math.round(avg(this.#pings)) | ||
const delta = Math.round(avg(this.#pings.map((d) => Math.abs(d - ping)))) | ||
|
||
// eslint-disable-next-line no-console | ||
console.debug( | ||
`Ping: ${ping}ms ±${delta}ms (${JSON.stringify(this.#pings)})`, | ||
) | ||
}) | ||
|
||
this.#timeout = setTimeout(this.#update.bind(this), 10000) | ||
} | ||
|
||
start() { | ||
this.stop() | ||
|
||
this.#timeout = setTimeout(this.#update.bind(this), 1000) | ||
} | ||
|
||
stop() { | ||
if (!this.#timeout) { | ||
return | ||
} | ||
|
||
clearTimeout(this.#timeout) | ||
this.#timeout = undefined | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
import { Socket } from 'socket.io-client' | ||
|
||
import { ClientToServerEvents, ServerToClientEvents } from '../shared/socket' | ||
|
||
export type ClientSocket = Socket<ServerToClientEvents, ClientToServerEvents> |