-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
91 lines (81 loc) · 2.63 KB
/
server.js
File metadata and controls
91 lines (81 loc) · 2.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
const net = require("net");
class McPing {
constructor(address, port) {
this.address = address;
this.port = port;
}
getData(callback) {
const start_time = new Date();
const client = net.connect(this.port, this.address, () => {
this.latency = Math.round(new Date() - start_time);
client.write(Buffer.from([0xfe, 0x01]));
});
client.setTimeout(5000);
client.on("data", (data) => {
if (data != null && data != "") {
const server_info = data.toString().split("\x00\x00\x00");
if (server_info != null && server_info.length >= 6) {
this.online = true;
this.version = server_info[2].replace(/\u0000/g, "");
this.motd = server_info[3].replace(/\u0000/g, "");
this.current_players = server_info[4].replace(
/\u0000/g,
""
);
this.max_players = server_info[5].replace(/\u0000/g, "");
} else {
this.online = false;
}
}
callback({
address: this.address,
port: this.port,
isOnline: this.online,
latency: this.latency,
version: this.version,
motd: this.motd,
current_players: this.current_players,
max_players: this.max_players
});
client.end();
});
client.on("timeout", () => {
callback({
error: { message: "Timed out" }
});
client.end();
});
client.on("end", () => {});
client.on("error", (err) => {
callback({ error: err });
});
}
}
const url = require("url");
const server = require("http").createServer((req, res) => {
try {
res.setHeader("Content-Type", "application/json");
const query = url.parse(req.url, true).query;
if (!query || !query.ip || !query.port) {
res.end(
JSON.stringify({
error: { message: "IP or PORT invalid!" }
})
);
return;
}
new McPing(query.ip, query.port).getData((response) => {
res.end(JSON.stringify(response));
});
} catch (err) {
console.log(err);
res.end(
JSON.stringify({
error: { message: "An error occurred!" }
})
);
}
});
server.listen(3000, () => {
console.log("running");
});