Skip to content

Commit 26b098a

Browse files
committed
Fix ping implement
1 parent 6c2204a commit 26b098a

File tree

2 files changed

+18
-10
lines changed

2 files changed

+18
-10
lines changed

src/index.d.ts

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -256,7 +256,7 @@ declare module 'minecraft-protocol' {
256256
}
257257

258258
export interface OldPingResult {
259-
maxPlayers: number,
259+
maxPlayers: number
260260
motd: string
261261
playerCount: number
262262
prefix: string
@@ -282,9 +282,11 @@ declare module 'minecraft-protocol' {
282282
protocol: number
283283
}
284284
favicon?: string
285-
latency: number
285+
latency?: number
286286
}
287287

288+
export type PingResult = OldPingResult | NewPingResult
289+
288290
export interface RealmsOptions {
289291
realmId?: string
290292
pickRealm?: (realms: Realm[]) => Realm
@@ -301,5 +303,5 @@ declare module 'minecraft-protocol' {
301303
export function createSerializer({ state, isServer, version, customPackets }: SerializerOptions): any
302304
export function createDeserializer({ state, isServer, version, customPackets }: SerializerOptions): any
303305

304-
export function ping(options: PingOptions, callback?: (error: Error, result: OldPingResult | NewPingResult) => void): Promise<OldPingResult | NewPingResult>
306+
export function ping(options: PingOptions, callback?: (error: Error, result: PingResult) => void): Promise<PingResult>
305307
}

src/ping.js

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -40,22 +40,28 @@ function ping (options) {
4040
client.once('server_info', function (packet) {
4141
const data = JSON.parse(packet.response)
4242
const start = Date.now()
43-
const maxTime = setTimeout(() => {
43+
const maxTimer = setTimeout(() => {
4444
clearTimeout(closeTimer)
4545
client.end()
4646
resolve(data)
4747
}, options.noPongTimeout)
48+
const time = BigInt(Date.now())
4849
client.once('ping', function (packet) {
4950
data.latency = Date.now() - start
50-
clearTimeout(maxTime)
51-
clearTimeout(closeTimer)
52-
client.end()
53-
resolve(data)
51+
if (BigInt(packet.time) === time) {
52+
// pong payload should be the same as ping payload
53+
clearTimeout(maxTimer)
54+
clearTimeout(closeTimer)
55+
client.end()
56+
resolve(data)
57+
}
5458
})
55-
client.write('ping', { time: [0, 0] })
59+
client.write('ping', { time })
5660
})
5761
client.on('state', function (newState) {
58-
if (newState === states.STATUS) { client.write('ping_start', {}) }
62+
if (newState === states.STATUS) {
63+
client.write('ping_start', {})
64+
}
5965
})
6066
// TODO: refactor with src/client/setProtocol.js
6167
client.on('connect', function () {

0 commit comments

Comments
 (0)