| 36 | } |
| 37 | |
| 38 | getStatus() { |
| 39 | return new Promise<MinecraftPingResponse>((resolve, reject) => { |
| 40 | var start_time = new Date().getTime(); |
| 41 | this.client = net.connect( |
| 42 | { |
| 43 | host: this.host, |
| 44 | port: this.port, |
| 45 | timeout: 1000 * 15 |
| 46 | }, |
| 47 | () => { |
| 48 | this.status.latency = Math.round(new Date().getTime() - start_time); |
| 49 | // 0xFE packet identifier for a server list ping |
| 50 | // 0x01 server list ping's payload (always 1) |
| 51 | let data = Buffer.from([0xfe, 0x01]); |
| 52 | this?.client?.write(data); |
| 53 | } |
| 54 | ); |
| 55 | |
| 56 | // The client can also receive data from the server by reading from its socket. |
| 57 | this?.client?.on("data", (response: any) => { |
| 58 | // Check the readme for a simple explanation |
| 59 | var server_info = response.toString().split("\x00\x00"); |
| 60 | |
| 61 | this.status = { |
| 62 | online: true, |
| 63 | host: this.host, |
| 64 | port: this.port, |
| 65 | version: server_info[2].replace(/\u0000/g, ""), |
| 66 | motd: server_info[3].replace(/\u0000/g, ""), |
| 67 | current_players: server_info[4].replace(/\u0000/g, ""), |
| 68 | max_players: server_info[5].replace(/\u0000/g, ""), |
| 69 | latency: this.status.latency |
| 70 | }; |
| 71 | |
| 72 | // Request an end to the connection after the data has been received. |
| 73 | this?.client?.end(); |
| 74 | resolve(this.status); |
| 75 | this.destroy(); |
| 76 | }); |
| 77 | |
| 78 | this?.client?.on("end", () => { |
| 79 | resolve(this.status); |
| 80 | this.destroy(); |
| 81 | }); |
| 82 | |
| 83 | this?.client?.on("error", (err: any) => { |
| 84 | reject(err); |
| 85 | this.destroy(); |
| 86 | }); |
| 87 | }); |
| 88 | } |
| 89 | |
| 90 | private destroy() { |
| 91 | this.client?.removeAllListeners(); |