From 26b098a8814bd9f03febc1f8cef437b23706bca6 Mon Sep 17 00:00:00 2001 From: SeaLoong Date: Sun, 13 Jul 2025 08:57:25 +0800 Subject: [PATCH] Fix ping implement --- src/index.d.ts | 8 +++++--- src/ping.js | 20 +++++++++++++------- 2 files changed, 18 insertions(+), 10 deletions(-) diff --git a/src/index.d.ts b/src/index.d.ts index e61d5403b..13e3993ac 100644 --- a/src/index.d.ts +++ b/src/index.d.ts @@ -256,7 +256,7 @@ declare module 'minecraft-protocol' { } export interface OldPingResult { - maxPlayers: number, + maxPlayers: number motd: string playerCount: number prefix: string @@ -282,9 +282,11 @@ declare module 'minecraft-protocol' { protocol: number } favicon?: string - latency: number + latency?: number } + export type PingResult = OldPingResult | NewPingResult + export interface RealmsOptions { realmId?: string pickRealm?: (realms: Realm[]) => Realm @@ -301,5 +303,5 @@ declare module 'minecraft-protocol' { export function createSerializer({ state, isServer, version, customPackets }: SerializerOptions): any export function createDeserializer({ state, isServer, version, customPackets }: SerializerOptions): any - export function ping(options: PingOptions, callback?: (error: Error, result: OldPingResult | NewPingResult) => void): Promise + export function ping(options: PingOptions, callback?: (error: Error, result: PingResult) => void): Promise } diff --git a/src/ping.js b/src/ping.js index f8328df1e..425752bd9 100644 --- a/src/ping.js +++ b/src/ping.js @@ -40,22 +40,28 @@ function ping (options) { client.once('server_info', function (packet) { const data = JSON.parse(packet.response) const start = Date.now() - const maxTime = setTimeout(() => { + const maxTimer = setTimeout(() => { clearTimeout(closeTimer) client.end() resolve(data) }, options.noPongTimeout) + const time = BigInt(Date.now()) client.once('ping', function (packet) { data.latency = Date.now() - start - clearTimeout(maxTime) - clearTimeout(closeTimer) - client.end() - resolve(data) + if (BigInt(packet.time) === time) { + // pong payload should be the same as ping payload + clearTimeout(maxTimer) + clearTimeout(closeTimer) + client.end() + resolve(data) + } }) - client.write('ping', { time: [0, 0] }) + client.write('ping', { time }) }) client.on('state', function (newState) { - if (newState === states.STATUS) { client.write('ping_start', {}) } + if (newState === states.STATUS) { + client.write('ping_start', {}) + } }) // TODO: refactor with src/client/setProtocol.js client.on('connect', function () {