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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
|
global.pingStart = null;
const sampleData = {
_type: "init",
name: "Kartik Core",
version: "21.04.5",
id: null,
modded: false
}
function crash(e) {
console.log("Communication error");
console.error(e);
process.exit(2);
}
function exit() {
process.exit();
}
var net = require('net');
var host = 'localhost';
var port = 8408;
var client = new net.Socket();
client.initialized = false;
client.connect(port, host, () => {
console.log("Connected to " + host + ":" + port);
client.write(JSON.stringify(sampleData));
//process.exit();
})
client.on('data', (data) => {
try {
d = data.toString();
try {
info = JSON.parse(d);
} catch(e) {
if (e.message.startsWith("Unexpected token")) {
info = JSON.parse(d.substr(0, e.message.split(" ")[e.message.split(" ").length - 1]));
}
}
} catch (e) {
crash(e)
}
if (typeof info['_type'] != "string") {
crash(new Error("Invalid JSON data"));
}
if (!client.initialized) {
switch (info['_type']) {
case "init":
if (info['name'] !== "Kartik Server") {
crash(new Error("Invalid server"));
}
console.log("Connection initialized. Server running " + info.name + " version " + info.version + ", client ID " + info.id);
client.initialized = true;
break;
case "error":
console.log(info['type'] + ": " + info['message']);
break;
default:
crash(new Error("Trying to receive data but client not initialized"));
break;
}
} else {
switch (info['_type']) {
case "init":
crash(new Error("Trying to initialize client but client is already initialized"));
break;
case "error":
console.log(info['type'] + ": " + info['message']);
break;
break;
case "linked":
console.log("Now hooked into link: (H) " + info['ids']['host'] + " <-> " + info['ids']['guest'] + " (G)");
setInterval(() => {
client.write(JSON.stringify({
_type: "ipc",
action: "Ping",
message: null
}))
global.pingStart = new Date();
}, 1000)
break;
default:
if (info['_type'] === "ipc" && info['action'] === "Ping") {
client.write(JSON.stringify({
_type: "ipc",
action: "Pong",
message: null
}))
return;
}
if (info['_type'] === "ipc" && info['action'] === "Pong") {
pingEnd = new Date();
ping = Math.round(pingEnd - pingStart);
global.pingStart = null;
console.log("Ping: " + ping + " ms");
return;
}
console.log("Data:");
console.dir(info);
break;
}
}
})
client.on('close', () => {
console.log("Kicked from server");
exit();
})
client.on('error', (e) => {
switch (e.code) {
case "ECONNREFUSED":
console.log("Unable to connect to server");
break;
default:
console.log("Internal error");
break;
}
crash(e);
})
|